TSQL组间隔时间为下午3点至下午3点

时间:2015-12-21 23:48:28

标签: sql-server tsql

我试图在今晚每天下午3点到下午3点获得订单数量

Select cast(order_datetime as date) ,count(*)
from order_table
where order_datetime> '01/01/2015 15:00'
group by ?????

我通常按

分组
cast(order_datetime as date) ---for 12am to 12am

但我希望下午3点到下午3点。

1 个答案:

答案 0 :(得分:0)

这可能是解决方案寻找我已采取样本数据和表变量@t来解决它表中的col1引用你的问题

SET DATEFORMAT DMY
DECLARE @t TABLE
(
Id int,
Name varchar(11),
[Col1] DateTime
)

INSERT INTO @t
VALUES(1,'ABC','22/12/2012 03:45:00 PM'),(2,'SD','22/12/2012 03:01:00 PM'),(3,'SDSA','22/12/2012 02:01:00 PM'),(4,'ASDF','22/12/2012 03:30:00 PM'),(5,'ASWER','22/12/2012 02:30:00 PM')
,(11,'NARI','21/12/2012 03:40:00 PM')

SELECT CASE  WHEN CAST(COL1 AS TIME) >'15:00:00' THEN CAST(DATEADD(DAY,1,Col1) AS date) ELSE CAST(Col1 AS DATE) END AS ORDERS,COUNT(*) AS COUNT
FROM @t
GROUP BY  CASE  WHEN CAST(COL1 AS TIME) >'15:00:00' THEN CAST(DATEADD(DAY,1,Col1) AS date) ELSE CAST(Col1 AS DATE) END