SQL-每天订购每件商品的次数

时间:2014-11-04 21:40:54

标签: sql sql-server

我有一张表格,其中包含itemIDorderTimedatetime)订单的日志。我知道我可以获得特定日期的特定物品的订单,如:

select 
   itemID, count(itemID) as Sep14 
from 
   tableName
where 
   itemID in (5, 6, 9)
   and orderTime between 'sep 14 2014 00:00:01' and 'sep 14 2014 23:59:59'
group by 
   itemID

我想要做的是获得相同的结果但是在更长的时间段内产生大量天数,因此输出类似于:

itemiD   Sep14   Sep15   Sep16
------   -----   -----   -----
5        0       2       1
6        3       3       0
9        2       1       2

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

select itemID, convert(DATE, orderTime), count(*)
from tableName
where itemID in (5, 6, 9)
and (orderTime > 'sep 14 2014 00:00:00' and orderTime < 'sep 21 2014 00:0:00')
group by itemId, convert(DATE, orderTime)

这将为您提供每天一行的结果。如果你试图每天获得一列,那么它就不会扩展。

答案 1 :(得分:0)

这将创建一个动态数据透视表,它将提供您想要的输出。它将为有数据的日期范围中的每个日期创建1列。如果您希望它包含没有数据的日期,则需要将其加入包含所有日期的日历表。

DECLARE @StartDate date = '20140101'
DECLARE @EndDate date = '20140102'

DECLARE @PivotColumnHeaders varchar(MAX)
SELECT @PivotColumnHeaders =
  COALESCE(
    @PivotColumnHeaders + ',[' + CONVERT(varchar(10),uc.orderTime,110) + ']',
    '[' + CONVERT(varchar(10),uc.orderTime,110) + ']'
  )
FROM (SELECT DISTINCT orderTime  FROM tablename WHERE orderTime BETWEEN @StartDate AND @EndDate) UC

DECLARE @PQuery varchar(MAX) = '
SELECT * FROM (SELECT ID, CAST(orderTime as date), Value FROM tablename T0 WHERE CAST(OrderTime as date) BETWEEN ''' + CONVERT(varchar(10),@StartDate,110) + ''' AND ''' + CONVERT(varchar(10),@EndDate,110) +''') T1
PIVOT (COUNT([Value]) FOR CAST(orderTime as date) IN (' + @PivotColumnHeaders + ') ) AS P'
EXECUTE (@PQuery)