我有這樣的資料,每個月有一個特定動物的月度計數。默認情況下,它在有資料的月份進行匯總。
然而,我希望每個動物的默認日期集,直到當前月的日期,如果沒有資料,則為0。希望的結果 -
是否有辦法在sql server上而不是在Excel中進行處理?
非常感謝您的到來。
uj5u.com熱心網友回復:
你可以使用數字表或遞回CTE(或日歷表)生成你想要的月份。 然后交叉連接與動物生成行,并使用左連接來引入現有的資料:
with dates as (
select min(date) as dte
from t
unionall
select dateadd(month, 1 dte)
from日期
where dte </span> getdate()
)
select a.animal, d.dte, coalesce(t.monthly_count, 0) as month_count
from dates d cross join
(select distinct animal from t) a left join
資料t
on t.date = d.dte and t.animal = a.animal
order by a.animal, d.dte。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/323131.html
標籤:
