具有范围的同一行中的多个计数

时间:2011-10-19 22:38:38

标签: sql sql-server-2008

我正在尝试获取开始日期和结束日期的一周内的交易数量。以下查询适用于一天2011-10-14

SELECT COUNT(operationId) AS trans
  FROM hwfg_t_Tracking 
  WHERE hitTime BETWEEN '2011-10-14 00:00:00' AND '2011-10-14 23:59:59.99'
GO

如何使用单个SELECT语句获取14,14,12,11,10,9,8(1周)之间hitTime的operationId计数。比如2011-10-14作为专栏的交易数量,2011-10-13作为另一个专栏等等

1 个答案:

答案 0 :(得分:2)

在指定范围内对每天一行进行以下查询:

SELECT cast(hitTime AS date) AS mydate, COUNT(operationId) AS trans
FROM   hwfg_t_Tracking
WHERE  hitTime >= '2011-10-14 00:00:00' AND hitTime < '2011-10-21 00:00:00'
GROUP  BY cast(hitTime AS date)

或者,如果您想要一行

SELECT COUNT(*) AS total_sum
      ,COUNT(CASE WHEN cast(dt As date) = '2011-10-14' THEN 1 ELSE NULL END) AS day14
      ,COUNT(CASE WHEN cast(dt As date) = '2011-10-15' THEN 1 ELSE NULL END) AS day15
      ,COUNT(CASE WHEN cast(dt As date) = '2011-10-16' THEN 1 ELSE NULL END) AS day16
-- etc.
FROM   hwfg_t_Tracking
WHERE  hitTime >= '2011-10-14 00:00:00' AND hitTime < '2011-10-21 00:00:00'