按时间间隔分组在sql中

时间:2011-04-06 15:55:29

标签: sql sql-server group-by

我需要在06:00-18:00和18:00-6:00之间同时显示数据

这是示例Query I M Using。我无法检索第二组数据。怎么做?

像 1, 2, 3 时间为06:00 - 18:00

和4, 5, 6 时间为18:00 - 06:00

SELECT     COUNT(cp.comm_pend_id) AS comm_pend_id, cp.UserID, um.Username, CONVERT(varchar, cp.submitted_date, 101) AS Date, SUM(cp.Earning) 
                      AS Earning, SUM(cp.total_commission) AS total_commission
FROM         dbo.comm_pending AS cp INNER JOIN
                      dbo.user_master AS um ON cp.UserID = um.UserID
GROUP BY cp.UserID, CONVERT(varchar, cp.submitted_date, 101), um.Username, cp.PaidStatus, CONVERT(varchar(10), cp.submitted_date, 108)
HAVING      (cp.PaidStatus = 'unpaid') AND (CONVERT(varchar(10), cp.submitted_date, 108) BETWEEN '06:00:00' AND '18:00:00')
ORDER BY cp.UserID

2 个答案:

答案 0 :(得分:0)

您无法检索第二组,因为18:00大于06:00,因此在同一天它们之间没有任何内容。对于第二组,您应该像这样过滤:

((CONVERT(varchar(10), cp.submitted_date, 108) < '06:00:00' 
 OR 
(CONVERT(varchar(10), cp.submitted_date, 108) > '18:00:00')

答案 1 :(得分:0)

CASE声明可能会有所帮助。例如:

create table #times (num int, dt datetime)

insert into #times values (1,'2011-4-6 0:00:00')
insert into #times values (2,'2011-4-6 4:00:00')
insert into #times values (3,'2011-4-6 8:00:00')
insert into #times values (4,'2011-4-6 12:00:00')
insert into #times values (5,'2011-4-6 16:00:00')
insert into #times values (6,'2011-4-6 20:00:00')

select 
    sum(case when (datepart(hh,dt) between 6 and 17) then num else 0 end) as daySum,
    sum(case when (datepart(hh,dt) not between 6 and 17) then num else 0 end) as nightSum
from #times