group by子句中多个字段的总和并创建单行

时间:2017-10-30 10:47:21

标签: sql sql-server

我有一张这样的桌子。

Id Name Test Subject   Marks
----------------------------
1  Alex 1    Maths     40
1  Alex 2    Maths     80
1  Alex 1    Sociology 55
1  Alex 2    Sociology 70
1  Alex 3    Sociology 60
2  Mark 1    Maths     30
2  Mark 2    Maths     60
2  Mark 1    Sociology 40
2  Mark 2    Sociology 50
2  Mark 3    Sociology 30

我需要的是一组中的Id,名称,主题和总和(标记)在一行中,给出如下结果:

Id Name Maths Sociology
-----------------------
1  Alex 120   185
2  Mark 90    120

我可以这样做:

Id Name Marks
--------------
1  Alex  120
2  Mark   90

或:

Id Name  Marks
-------------
1  Alex  185
2  Mark  120

我尝试了多个选项,但我为每个ID获取了多行。

以下查询无效:

select 
    Id, Name, Sum(Marks) where Subject = 'Maths' as Maths,Sum(Marks ) where Subject = 'Sociology' as Sociology
from 
    Table
group by 
    Id, Name;

我收到此错误:

  

"编译语句时出错:FAILED:ParseException line 3:66 EOF at' as'靠近数学'

4 个答案:

答案 0 :(得分:1)

您可以使用case表达式有效过滤进入sum的值:

select Id
      ,Name
      ,sum(case when Subject = 'Maths' then Marks else 0 end) as Maths
      ,sum(case when Subject = 'Sociology' then Marks else 0 end) as Sociology
from Table
group by Id
        ,Name;

如果您希望在很多不同的subject值中执行此操作,则需要查看使用pivot

select Id
      ,[Name]
      ,[Maths]
      ,[Sociology]
from (select Id, [Name], [Subject], Marks from @t) as t
pivot(sum(Marks)
      for [Subject] in(Maths,Sociology)
    ) as p;

答案 1 :(得分:1)

您正在寻找PIVOT。试试:

create table #tbl(Id int, Name varchar(20), Test int, Subject varchar(20), Marks int)
insert into #tbl values
(1,'Alex',1,'Maths', 40    ),
(1,'Alex',2,'Maths', 80    ),
(1,'Alex',1,'Sociology', 55),
(1,'Alex',2,'Sociology', 70),
(1,'Alex',3,'Sociology', 60),
(2,'Mark',1,'Maths', 30    ),
(2,'Mark',2,'Maths', 60    ),
(2,'Mark',1,'Sociology', 40),
(2,'Mark',2,'Sociology', 50),
(2,'Mark',3,'Sociology', 30)

--select * from #tbl

SELECT ID,Name,Maths,Sociology
FROM(
    SELECT ID, Name, Subject, Marks
    FROM #tbl
    ) tbl
PIVOT(
    SUM(Marks) FOR Subject IN (Maths, Sociology)
) piv

输出:

ID          Name  Maths       Sociology
----------- ---- ------------ -----------
1           Alex  120         185
2           Mark  90          120

答案 2 :(得分:0)

使用PIVOT运算符的另一种解决方案:

SELECT
    ID
    ,Name
    ,Maths
    ,Sociology
FROM(
    SELECT
        ID
        ,Name
        ,Subject
        ,Marks
    FROM your_table
) tbl
PIVOT(
    SUM(Marks) FOR Subject IN (Maths, Sociology)
) pvt

答案 3 :(得分:0)

您可以使用以下查询:

select id,name,maths_marks,sociology_marks
from
(select id,name,test,subject,marks
from table)
pivot(sum(marks) for subject in ('Maths' as Maths_marks,'Sociology' as Sociology_marks);