试试这个 - :(一年中的第一个日期到当前日期),但如果你想要 365 天,那么将查询中的 getdate() 替换为一年中的最后一个日期。
WITH mycte AS
(
SELECT cast(DATEADD(yy, year(GETDATE()) - 1900, 0) as datetime) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue + 1 < getdate()
)
SELECT cast(DateValue as date) as [Date],'boot' as Shoe_type,isnull([open],0) as [Open]
FROM mycte a left join (select cast(dt as date) as date,shoe_type,count(*) as [open] from YOURTABLENAME where state='open' and shoe_type='boot' group by cast(dt as date),shoe_type ) b
on cast(DateValue as date)=b.date
union
SELECT cast(DateValue as date) as [Date],'sandal' as Shoe_type,isnull([open],0) as [Open]
FROM mycte a left join (select cast(dt as date) as date,shoe_type,count(*) as [open] from YOURTABLENAME where state='open' and shoe_type='sandal' group by cast(dt as date),shoe_type ) b
on cast(DateValue as date)=b.date
union
SELECT cast(DateValue as date) as [Date],'trainer' as Shoe_type,isnull([open],0) as [Open]
FROM mycte a left join (select cast(dt as date) as date,shoe_type,count(*) as [open] from YOURTABLENAME where state='open' and shoe_type='trainer' group by cast(dt as date),shoe_type ) b
on cast(DateValue as date)=b.date
union
SELECT cast(DateValue as date) as [Date],'shoe' as Shoe_type,isnull([open],0) as [Open]
FROM mycte a left join (select cast(dt as date) as date,shoe_type,count(*) as [open] from YOURTABLENAME where state='open' and shoe_type='shoe' group by cast(dt as date),shoe_type ) b
on cast(DateValue as date)=b.date
OPTION (MAXRECURSION 0)