SQL Server使用范围创建输出表

时间:2018-05-31 08:59:22

标签: sql sql-server range

我有以下查询:

select a.ID, a.Date_Reported AS [Date Sent to X],  b.Date_Received AS [Date Returned from X], 

(datediff(dd, a.date_reported, b.date_received) 
      + CASE WHEN Datepart(dw, b.date_received) = 7 THEN 1 ELSE 0 END 
       - (Datediff(wk, a.date_reported, b.date_received) * 2 ) 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 END + 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 
       END) AS [Time_Spent]

from Tx_Ex a 
join Tx b on b.id = a.id

简单地说,查询的作用是在两个表格中找到两个日期(收到日期 - 报告日期)之间的工作日差异。

我想调整查询,以便我的输出如下所示:

Time Taken (days) | 0-3 | 4 | 5 | 6-8 | 9+ | less than 0 days
Count             |  2  | 1 | 2 | 1   | 1  | 3
%                 | 20  | 10| 20| 10  | 10 | 30

基本上,我只是为count和%添加了虚拟值,以便更好地了解我想要的内容。基本上,我想调整上面的查询,所以我有上面的范围,还有其他两个带有count和%的行。

上表中的示例,查询将告诉我有两个实例,其中两个日期的差异在0-3范围内,因此总计数的20%。此外,还有一些情况(由于错误),其中所用的时间可能是负的(即报告的日期实际上晚于收到的日期),这就是为什么我添加了"小于0的范围"

如果有任何不清楚的地方,请告诉我。

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合将结果放在一行(而不是两行)中:

with t as (
      <your query here>
     )
select sum(case when time_spent < 0 then 1 else 0 end) as days_lt_0,
       sum(case when time_spent between 0 and 3 then 1 else 0 end) as days_0_3,
       sum(case when time_spent 4 then 1 else 0 end) as days_4,
       sum(case when time_spent 5 then 1 else 0 end) as days_5,
       sum(case when time_spent between 6 and 8 then 1 else 0 end) as days_6_38,
       sum(case when time_spent >= 9 then 1 else 0 end) as days_9pl,
       avg(case when time_spent < 0 then 1.0 else 0 end) as ratio_lt_0,
       avg(case when time_spent between 0 and 3 then 1.0 else 0 end) as ratio_0_3,
       avg(case when time_spent 4 then 1.0 else 0 end) as ratio_4,
       avg(case when time_spent 5 then 1.0 else 0 end) as ratio_5,
       avg(case when time_spent between 6 and 8 then 1.0 else 0 end) as ratio_6_38,
       avg(case when time_spent >= 9 then 1.0 else 0 end) as ratio_9pl
from t;