如何让没有记录的月份的计数显示为零

xoefb8l8  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(274)

我在属性(表1235中的属性id 4205)发生更改的日期(在历史记录表中找到)之前拉取发生在该属性上的事务,并按月计算发生的更改数。到目前为止我已经

SELECT TOP(100) PERCENT MONTH(H.transactiondate) AS Month, COUNT(*) AS Count 
FROM hsi.rmObjectInstance1235 AS O LEFT OUTER JOIN 
     hsi.rmObjectHistory AS H ON H.objectID = O.objectID 
WHERE H.attributeid = 4205) AND Year(H.transaction date) = '2020' 
GROUP BY MONTH(H.transactiondate)

我得到了

Month    Count 
---------------
1        9 
2        4 
3        11
4        14
5        1

我需要为六月到十二月的月份显示一个零,而不是排除那些月份。

t0ybt7op

t0ybt7op1#

一个选项使用递归查询生成日期,然后将原始查询与 left join :

with all_dates as (
    select cast('2020-01-01' as date) dt
    union all
    select dateadd(month, 1, dt) from all_dates where dt < '2020-12-01'
)
select
    month(d.dt) as month, 
    count(h.objectid) as cnt
from all_dates d
left join hsi.rmobjecthistory as h 
    on  h.attributeid = 4205
    and h.transaction_date >= d.dt
    and h.transaction_date < dateadd(month, 1, d.dt)
    and exists (select 1 from hsi.rmObjectInstance1235 o where o.objectID = h.objectID)
group by month(d.dt)

我不太清楚这张table的用意 hsi.rmObjectInstance1235 在查询中,因为没有在 select 以及 group by 条款;它是用来过滤的 hsi.rmobjecthistoryobjectID ,然后您可以将其重写为 exists 条件,如上述解决方案所示。可能的话,您也可以删除查询的这一部分。
另外,请注意 top 没有 order by 真的说不通 top (100) percent 是不可能的
因此,我删除了行限制条款。

相关问题