如何更改此表
Name subject Mark
Aswin physics 100
Aswin chemistry 300
Aswin maths 200
向
Aswin Physics 100 Chemistry 300 Maths 200
任何人请帮帮我。
答案 0 :(得分:2)
答案 1 :(得分:2)
select Name,
sum(CASE
when [subject]='physics' then Mark
end) as Physics,
sum(CASE
when [subject]='chemistry' then Mark
end) as chemistry,
sum(CASE
when [subject]='maths' then Mark
end) as maths
from t group by Name
或者如果您需要一行:
SELECT
t1.name,
MemberList = substring((SELECT ( ', ' + subject+' - '+
cast(Mark as varchar(100)) )
FROM t t2
WHERE t1.name = t2.name
ORDER BY
name,
subject
FOR XML PATH( '' )
), 3, 1000 )FROM t t1
GROUP BY name
答案 2 :(得分:1)
您需要使用SQL Pivoting,请查看SQL SERVER – PIVOT and UNPIVOT Table Examples处的示例。使用Sql Pivoting可以将行更改为列,而Unpivoting则用于列到行的转换。
请注意:我正在检查我是否能为您提供确切的脚本,但现在该链接可以帮助您。
代码示例
虽然我没有用实际数据对此进行测试,但它解析得很好。
-- Pivot Table ordered by Name of Student
SELECT Name, Physics, Chemistry, Maths
FROM (
SELECT Name, Subject, Mark
FROM Student) up
PIVOT (SUM(Mark) FOR Student IN (Physics, Chemistry, Maths)) AS pvt
ORDER BY Name
-- Result should be something like
----------------------------------
Name Physics Chemistry Maths
----------------------------------
Aswin 100 300 200
----------------------------------
要创建数据透视,您需要知道要转换为列的实际行值。 我之前写过关于动态旋转here的文章,如果你发现它有用的话。
答案 3 :(得分:1)
目前尚不清楚您是希望将这些数据放在单独的列中还是列在一列中。
如果您希望在单独的列中进行此操作,则可以应用SQL Server 2005中可用的PIVOT
函数。
如果您知道要转换的所有值或数量有限的值,那么您可以对查询进行硬编码:
select *
from
(
select name, subject +' '+ cast(mark as varchar(9)) as sub_mark,
'Subject_'+cast(row_number() over(partition by name
order by subject) as varchar(10)) col_name
from subjects
) s
pivot
(
max(sub_mark)
for col_name in (Subject_1, Subject_2, Subject_3)
) piv;
见SQL Fiddle with Demo。您会注意到我与其他 pivot 答案略有不同。我将主题/标记放在同一列中,列名为Subject_1
等。
如果您有不确定数量的值,则可以使用动态sql:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Subject_'+cast(row_number() over(partition by name
order by subject) as varchar(10)))
from subjects
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name,' + @cols + ' from
(
select name, subject +'' ''+ cast(mark as varchar(9)) as sub_mark,
''Subject_''+cast(row_number() over(partition by name
order by subject) as varchar(10)) col_name
from subjects
) x
pivot
(
max(sub_mark)
for col_name in (' + @cols + ')
) p '
execute(@query)
见SQL Fiddle with Demo。如果name
有超过3个主题,动态sql版本的列数会增加。
两个查询的结果是:
| NAME | SUBJECT_1 | SUBJECT_2 | SUBJECT_3 |
---------------------------------------------------
| Aswin | chemistry 300 | maths 200 | physics 100 |