每天的记录计数,按用户比较

时间:2018-09-21 18:16:52

标签: sql sql-server

希望查看是否可以比较特定用户(EDI)或其他任何人一天输入的订单数量。

我可以每天返回结果(但只能返回存在值的日子),但无法找到一种将所有三个结果组合在一起的方法(总计-通过EDI-其他所有人)。

非常感谢任何帮助。

select Date, count(Order_ID) 
from orders 
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) and [user] = 'EDI' 
      and customer = '9686'
GROUP BY Date, [user];
select Date, count(Order_ID) 
from orders 
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) and [user] <> 'EDI' 
      and customer = '9686'
GROUP BY Date, [user];
select Date, count(Order_ID) 
from orders 
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) 
      and customer = '9686'
GROUP BY Date, [user];

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

select Date, sum(case when [user] = 'EDI' then 1 else 0 end) as cnt_edi,
       sum(case when [user] <> 'EDI' then 1 else 0 end) as cnt_non_edi,
       count(*) as total
from orders 
where Date >= dateadd(day, datediff(day, 0, GetDate()) - 7, 0) and customer = '9686'
group by Date;