0

我有一张叫shoe_service的桌子

简化表

取取消表示虚假交易或错误,不计入。将 closed_at 设为 null 表示它尚未关闭。我已经能够使用以下方法找到在特定日期开放的交易数量:

我试过的SQL代码

这将返回我想要的确切数据:

预期返回数据

但是,我不希望它只在我必须手动输入和更改的特定日子。我想要一个为每一天和鞋子类型返回一行的表格。

IE

我想看到的一个例子

我希望有 1460 (=4*365) 行数据。本质上,我想打开我的查询来为每一天扩展它,而不仅仅是我输入的单个时间戳。数据通过时间戳记录。

我想我必须做某种顺序日期加入,但我不知道该怎么做?

抱歉无法嵌入图片

4

2 回答 2

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)
于 2018-07-18T12:30:41.550 回答
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)

于 2018-07-17T10:32:21.173 回答