我的表格列为:
Sr.no Subject No of class attended
-------------------------------------
1 English 3
2 Maths 4
3 SocialScience 5
我希望这种格式的表格
English Maths SocialScience
---------------------------------
3 4 5
我试过了:
Select case when subject ='Maths' then COUNT(No_of_Candidates) else null end as Maths
但是我得到了这样的数据:
English Maths SocialScience
---------------------------------
3
4
5
请帮我解决这个问题。
答案 0 :(得分:6)
正如你所说,你不希望这样的输出:
English Maths SocialScience
---------------------------------
3
4
5
您需要使用这样的子查询:
SELECT English,Maths,SocialScience
FROM (
SELECT Subject,No_of_class_attended
FROM mytable) up
PIVOT
(Sum([No_of_class_attended])
for Subject in ([English],[Maths],[SocialScience])) p
输出:
English Maths SocialScience
---------------------------------
3 4 5
答案 1 :(得分:2)
使用PIVOT
SELECT *
FROM yourtable
PIVOT
(Sum([No of class attended]) for Subject in ([English],[Maths],[SocialScience])) p
答案 2 :(得分:2)
podiluska解决方案是正确的,如果您想将其他主题添加到表中,并且不想更改查询,我只想分享动态解决方案。但是它在长度方面有一些限制,但你可以肯定地在某些情况下使用它:
DECLARE @SQL nvarchar(MAX)
DECLARE @ColNames nvarchar(max)
SET @ColNames = ''
SELECT @ColNames = (CASE WHEN subjects.Subject IS NOT NULL THEN @ColNames + '[' + subjects.Subject + '],' ELSE '' END)
FROM subjects
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)
EXEC('SELECT *
FROM subjects
PIVOT
(Sum([classNum]) for Subject in (' + @ColNames + ')) p')
这是SQL Fiddle。
答案 3 :(得分:1)
如果您不想使用PIVOT关键字,只需使用MAX:
Select MAX(case when subject ='Maths' then No_of_Candidates else null end) as Maths
,MAX(case when subject ='English' then No_of_Candidates else null end) as English
,MAX(case when subject ='SocialScience' then No_of_Candidates else null end) as SocialScience
from tableName
例如,如果表包含多个学生的结果,则需要使用GROUP BY,例如:
Select MAX(case when subject ='Maths' then No_of_Candidates else null end) as Maths
,MAX(case when subject ='English' then No_of_Candidates else null end) as English
,MAX(case when subject ='SocialScience' then No_of_Candidates else null end) as SocialScience
from tableName Group By StudentID
任何值都大于NULL,因此MAX将消除NULL
答案 4 :(得分:0)
所以我遇到了将行转置为列的要求,在此我想根据数据动态增加列(而不是像英格兰,数学等那样对它们进行硬编码)
这是我的 Sample Data
代码:
<button id="clickMe">Click for 10 seconds</button>