简体   繁体   English

在SQL中按时间间隔分组

[英]group by time interval in sql

I need to show data between time 06:00 - 18:00 and 18:00 - 06:00 at same time 我需要在06:00-18:00和18:00-06:00之间同时显示数据

this is sample Query IM Using. 这是查询IM使用示例。 I can not retrieve second group data. 我无法检索第二组数据。 How to do? 怎么做?

like 1, 2, 3 comes in 06:00 - 18:00 range 像1,2,3在06:00-18:00范围内

and 4, 5, 6 comes in 18:00 - 06:00 range 和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

You cannot retrieve the second group because 18:00 is greater than 06:00, so there's nothing between them in the same day. 您无法检索第二组,因为18:00大于06:00,因此同一天它们之间没有任何内容。 For the second group you should filter like this: 对于第二组,您应该像这样进行过滤:

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

A CASE statement might be able to help. CASE语句可能会有所帮助。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM