按天和小时分组的t-SQL

时间:2017-02-14 13:44:48

标签: sql sql-server tsql

我需要确定本周和周末的销售数量,但周末应计算在周五下午6点到周一上午9点​​之间。

例如,如果我有以下数据:

2017-02-09 14:00
2017-02-09 19:00
2017-02-10 17:15
2017-02-10 18:22
2017-02-11 11:00
2017-02-11 16:00
2017-02-12 19:30
2017-02-13 08:00
2017-02-14 14:00

我会得到以下内容:

Weekday: 4
Weekend: 5

使用类似的东西很容易获得每天的销售额

select count(*) as total, dateadd(DAY,0, datediff(day,0, created) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))

但我想不出如何结合时间和天数来获取我需要的信息。

4 个答案:

答案 0 :(得分:2)

这只是一个复杂的case语句。您可以使用outer apply执行此操作并使用聚合值:

select weekpart, count(*)
from sales s outer apply
     (values (case when datename(dw, created) in ('Tuesday', 'Wednesday', 'Thursday') then 'Weekday'
                   when datename(dw, created) = 'Monday' and 
                        datepart(hh, created) >= 9
                   then 'Weekday'
                   when datename(dw, created) = 'Friday' and 
                        datepart(hh, created) < 18
                   then 'Weekday'
                   else 'Weekend'
               end)
      ) v(weekpart)
group by v.weekpart;

故意在工作日使用datename()。星期几受国际化设置的影响。所有英语国家/地区的工作日都具有相同的名称,但当地会议可能会影响本周开始的日期。我还认为,对于非英语设置,代码非常明确,为什么它不起作用 - 与“1”的比较不是。

答案 1 :(得分:1)

尝试类似的东西:

SELECT week_or_weekend, count(*)
FROM
(
    SELECT 1 as cnt, CASE WHEN 
    DATEPART(DW, created) in (7,1)
    OR
    (DATEPART(DW, created) 6 AND DATEPART(hour, created) >= 18)
    OR
    (DATEPART(DW, created) 2 AND DATEPART(hour, created) < 9)
    THEN 'WEEKEND'
    ELSE 'WEEK'
    END week_or_weekend 
    FROM sales
) q
GROUP BY week_or_weekend

说明: DW = 7代表星期六,1代表星期日,6代表星期五,2代表星期一 除非你在子查询中添加一个不同的东西,否则我添加1作为cnt以澄清它是无用的。 您可以在1个查询中执行此操作,但是您必须重复两次“结束时”声明的大案例。

答案 2 :(得分:1)

with CTE as
(
select created,
  case when 
   (datepart(dw,[created]) = 6 and  datepart(hh,created) >= 18) or
   (datepart(dw,created)=7 or datepart(dw,created)=1) or 
   (datepart(dw,[created]) = 2 and  datepart(hh,created) <= 9)
   then 'Weekend'
  else 'Weekday' end as weekType
 from Table1)
 select weekType, count(1)
 from CTE
 group by weekType

在此处查看:http://sqlfiddle.com/#!6/4fbb0/8

答案 3 :(得分:0)

这将帮助您入门:

with CTE as
(
select dateadd(hh, datepart(hh,created), dateadd(dd,0, datediff(dd,0,created))) as created_dayhour, 
       someothercolumn, 
       datepart(dw,created) as create_day, 
       datepart(hh, created) as create_hour
from sales
)
select created_dayhour, count(someothercolumn)
from CTE
group by created_dayhour