SQL中的行总和与平均值和差异

时间:2018-08-08 09:57:03

标签: sql-server sql-server-2008

必需的输出:

 PName      Total   Average Difference
 GSU         20       25       5
 MST         30       25      -5
Costruct     25       25       0

表格值

  PName      cost
  GSU       10
  MST       15
  GSU       10
  Constuct  25
  MST       15

查询

 SELECT PName, SUM(cost) AS cost  FROM [Table_name] group by  PName

我的查询给了我前两列,我还需要平均值差异

如何从Sql Query中获取它?

3 个答案:

答案 0 :(得分:3)

这应该有效:

WITH Tab AS
(
  SELECT * FROM (VALUES
  ('GSU'     , 10),
  ('MST'     , 15),
  ('GSU'     , 10),
  ('Constuct', 25),
  ('MST'     , 15)) T(pname, cost)
)
SELECT
    pname,
    SUM(cost) Total,
    MAX(TotalSum)/COUNT(*) OVER() Average,
    MAX(TotalSum)/COUNT(*) OVER()-SUM(cost) Difference
FROM (
  SELECT cost, pname, SUM(cost) OVER () TotalSum
  FROM Tab
) T GROUP BY pname

输出(未排序):

pname    Total       Average     Difference
-------- ----------- ----------- -----------
Constuct 25          25          0
GSU      20          25          5
MST      30          25          -5

答案 1 :(得分:2)

SELECT t1.PName, SUM(t1.Cost) AS Total, t2.AvgCost, t2.AvgCost-SUM(t1.Cost) AS Diff
FROM Table t1,
(SELECT avg(cost) AS AvgCost FROM Table) t2
GROUP BY t1.PName

答案 2 :(得分:2)

嗨,Pravin,这是您想要的查询:

select 
Pname, 
sum(cost) as Total, 
sum(cost)/count(cost) as Average, 
sum(cost) - sum(cost)/count(cost) as Difference 
from [Table_name]  
group by Pname