我使用了以下查询
select month(SubmittedDate), count(policyid) from tblpolicy p join tlkppolicystatus s on p.StatusID=s.StatusID where SubmittedDate between
'2017-01-01' and sysdate() and s.StatusID=1 group by month(SubmittedDate);
这将返回以下输出,该输出正确为月号3和4没有任何数据。
Month Total
-----|-----
1 | 62
2 | 34
5 | 1
但我希望输出像
Month Total
-----|-----
1 | 62
2 | 34
3 | 0
4 | 0
5 | 1
这意味着如果任何月份有任何数据,那么它也将显示值0
由于
答案 0 :(得分:0)
试试这个
select coalesce(t1.month,t2.month) as month, coalesce(ct1.count,0) as count from
(
select month(SubmittedDate) as month, count(policyid) as count
from tblpolicy p join tlkppolicystatus s on p.StatusID=s.StatusID
where SubmittedDate between
'2017-01-01' and sysdate() and s.StatusID=1 group by month(SubmittedDate)
) as t1 right join
(
select 1 as month union all
select 2 as month union all
select 3 as month union all
select 4 as month union all
select 5 as month union all
select 6 as month union all
select 7 as month union all
select 8 as month union all
select 9 as month union all
select 10 as month union all
select 11 as month union all
select 12 as month
) as t2 on t1.month <= t2.month;
答案 1 :(得分:0)
如果您有所有月份的数据,但没有数据的状态为1,那么最简单的方法可能是使用条件聚合:
select month(SubmittedDate), sum(s.StatusID = 1)
from tblpolicy p join
tlkppolicystatus s
on p.StatusID=s.StatusID
where SubmittedDate between '2017-01-01' and sysdate()
group by month(SubmittedDate);
当然,如果这些条件不成立,那么带有派生表的left join
是最佳解决方案。