1

我想获取周一到周日的订购商品数量,但是将周六和周日的订单添加到周五,所以查询结果只会显示 Orderdates (Monday to Friday)

我已经有这个 sql 显示一周中每一天的订单:

select DATENAME(weekday,orderdate) Day,CONVERT(VARCHAR(10), orderdate, 103) orderdate, 
COUNT(orderdate) Orders  
from Orders_tb
where orderDate >= '2012-03-01 00:00:00.000'  
and orderDate <= '2012-03-31 00:00:00.000'  
group by datepart(day,orderDate),orderdate,DATENAME(weekday,orderdate)

感谢您的输入!

4

1 回答 1

1

澄清后编辑。

用例将周末更改为星期五。派生表用于避免在需要 orderdate 的任何地方复制相同的表达式。

select DATENAME(weekday,orderdate_trimmed) Day,
       CONVERT(VARCHAR(10), orderdate_trimmed, 103) orderdate, 
       COUNT(orderdate_trimmed) Orders
from 
(
  select *, 
         order_date -
         case DATENAME(weekday,orderdate)
              when 'Saturday' then 1
              when 'Sunday' then 2
              else 0
          end
         orderdate_trimmed
    from Orders_tb
) a
where orderDate >= '2012-03-01 00:00:00.000'
  and orderDate <= '2012-03-31 00:00:00.000'
group by orderdate_trimmed

您可以仅通过使用 case 语句来计算匹配天数:

select COUNT(orderdate) TotalOrders,
       COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Monday' then 1 end) Monday,
       COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Tuesday' then 1 end) Tuesday,
       COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Wednesday' then 1 end) Wednesday,
       COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Thursday' then 1 end) Thursday,
       COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Friday' 
                    OR DATENAME(weekday,orderdate) = 'Saturday' 
                    OR DATENAME(weekday,orderdate) = 'Sunday'
                  THEN 1 end) Friday
from Orders_tb
where orderDate >= '2012-03-01 00:00:00.000'  
and orderDate <= '2012-03-31 00:00:00.000'  

关于日期的警告:由于日期可以包含时间部分,这样比较会更明智:

where orderDate >= '2012-03-01 00:00:00.000'  
and orderDate < '2012-04-01 00:00:00.000'  
于 2012-04-18T11:52:10.377 回答