我有一个名为 shoe_service
的表
被取消表示错误的交易或错误,不予计算。将null的closed_at表示尚未关闭。 我已经能够使用以下命令找到特定日期有多少笔交易:
这将返回我想要的确切数据:
但是我不想只在特定的日子里需要手动输入和更改。 我想要一张表格,该表格针对每一天和鞋子的类型返回一行。
即
我希望有1460(= 4 * 365)行数据。 本质上,我想打开我的查询以将其扩展到每一天,而不仅仅是我输入的单个时间戳。数据通过时间戳记录。
我想我必须进行某种顺序的日期联接,但是我不确定该怎么做?
很抱歉无法嵌入图片
答案 0 :(得分:0)
请尝试以下查询。
select cast(opened_at as date) as date,shoe_type,count(*) as [open] from shoeTable where state='open' group by cast(opened_at as date),shoe_type order by cast(opened_at as date)
答案 1 :(得分:0)
尝试以下一个::(一年中的第一个日期到当前日期),但是如果需要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)