下载包括下载时间,下载时间ID和buno ID.
故障由故障代码,下载时间ID,状态和类型组成.下载可能有许多错误,可以加载下载时ID.
故障由故障代码,下载时间ID,状态和类型组成.下载可能有许多错误,可以加载下载时ID.
给定一组故障代码,结果必须包含每个具有相应故障计数的故障代码.如果在下载中未找到故障代码,则必须返回故障代码,故障计数为零.
问题似乎需要一个OUTER JOIN,但是没有看到它在Postgres上按预期工作,因为它似乎没有从LEFT表返回带有空值的集合.
查询如下,为简洁起见省略了一些细节:
SELECT f.faultcode,f.downloadtimeid,d.downloadtime,count(*) as faultcount FROM download_time d LEFT OUTER JOIN fs_fault f ON f.downloadtimeid = d.id AND f.faultcode IN (1000,1100) AND f.statusid IN(2,4) WHERE (d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012') AND d.bunoid = 166501 GROUP BY d.bunoid,f.faultcode
第二天,我编辑了以显示答案.所有答案都很接近,并有各种各样的帮助.然而,JayC的答案是最接近的.这是最终的sql,只有作为WHERE子句采用故障代码IN语句的更改:
SELECT f.faultcode,count(*) as faultcount FROM download_time d RIGHT OUTER JOIN fs_fault f ON f.downloadtimeid = d.id AND f.statusid IN(2,4) AND d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012' AND d.bunoid = 166501 WHERE f.faultcode IN (1000,1100) GROUP BY d.bunoid,f.faultcode
谢谢,一切都是为了你的帮助!喜欢这个网站!
解决方法
我给出了答案,因为我对其他答案有很大疑问.你必须小心过滤器的要求.请记住,where子句在您加入后运行.因此,如果where子句中有任何过滤器要求引用非外连接表,则(在许多情况下)使外连接无效.所以拿你的sql,似乎最简单的解决方案是使用正确的连接或适当地移动表名,然后将过滤条件移出where子句并进入join子句.
SELECT f.faultcode,count(*) as faultcount FROM download_time d RIGHT OUTER JOIN fs_fault f ON f.downloadtimeid = d.id AND f.faultcode IN (1000,4) AND d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012') AND d.bunoid = 166501 GROUP BY d.bunoid,f.faultcode
我认为应该相同的另一种方式是
SELECT f.faultcode,count(*) as faultcount FROM download_time d RIGHT OUTER JOIN fs_fault f ON f.downloadtimeid = d.id AND d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012') AND d.bunoid = 166501 WHERE f.faultcode IN (1000,4) GROUP BY d.bunoid,f.faultcode
因为fs_fault的过滤器要求不严格. (而你的sql引擎无论如何都会改变这一点).
编辑:这是一个SQLFiddle演示过滤子句与where子句的过滤.