新列的Sql总和

时间:2018-06-05 08:59:24

标签: sql-server sum

我在下面有一个查询的一部分,我根据条件创建了新列:

select 
   sum(case when Overall_Time_Spent < 0 then 1 else 0 end) as Errors,
   sum(case when Overall_Time_Spent between 0 and 3 then 1 else 0 end) as _0_3_days,
   sum(case when Overall_Time_Spent = 4 then 1 else 0 end) as _4_days,
   sum(case when Overall_Time_Spent = 5 then 1 else 0 end) as _5_days,
   sum(case when Overall_Time_Spent between 6 and 8 then 1 else 0 end) as _6_8_days,
   sum(case when Overall_Time_Spent >= 9 then 1 else 0 end) as more_than_9_days,

   avg(case when Overall_Time_Spent < 0 then 100.0 else 0 end) as Errors_percent,
   avg(case when Overall_Time_Spent between 0 and 3 then 100.0 else 0 end) as _0_3_percent,
   avg(case when Overall_Time_Spent = 4 then 100.0 else 0 end) as _4_percent,
   avg(case when Overall_Time_Spent = 5 then 100.0 else 0 end) as _5_percent,
   avg(case when Overall_Time_Spent between 6 and 8 then 100.0 else 0 end) as _6_8_percent,
   avg(case when Overall_Time_Spent >= 9 then 100.0 else 0 end) as more_than_9_days_percent,

如何在这个中添加一个查询,我可以添加两个以上的列,这些列给出了所有平均值和所有平均值的总和

提前致谢

2 个答案:

答案 0 :(得分:3)

CASE表达<008>=9之间的int表达式,每种可能性,只要您的数据是COUNT(Overall_Time_Spent) AS DaysTotal 。因此,您需要添加的是

int

如果它不是CASE,那么您的3表达式将会错过445和{{1}之间的值}},56以及89但是,COUNT会包含它们。

答案 1 :(得分:1)

尝试使用子查询:

SELECT a.*, (Errors + _0_3_days...) as Total FROM (
select 
   sum(case when Overall_Time_Spent < 0 then 1 else 0 end) as Errors,
   sum(case when Overall_Time_Spent between 0 and 3 then 1 else 0 end) as _0_3_days,
   sum(case when Overall_Time_Spent = 4 then 1 else 0 end) as _4_days,
   sum(case when Overall_Time_Spent = 5 then 1 else 0 end) as _5_days,
   sum(case when Overall_Time_Spent between 6 and 8 then 1 else 0 end) as _6_8_days,
   sum(case when Overall_Time_Spent >= 9 then 1 else 0 end) as more_than_9_days
) as a