sql数据横向
A. 如何把sql的结果横向显示
如果你想将SQL查询的结果横向显示,你可以使用PIVOT操作符。PIVOT操作符允许你将行转换为列,从而使结果更易于阅读和分析。以下是一个示例查询:
SELECT *FROM (SELECT name, subject, scoreFROM grades) AS srcPIVOT (MAX(score)FOR subject IN ('math', 'english', 'history')) AS pvt
这将返回一个结果集,其中每个学生的姓名都是一行,每个科目的成绩都是一列。你可以根据需要修改查询以满足你的需求。
B. sql语句 把纵向的数据变成横向
declare @A table(字段1 varchar(1), 字段2 int)
insert into @A
select 'A',1 union all
select 'A',2 union all
select 'A',3 union all
select 'A',4 union all
select 'A',5 union all
select 'B',1 union all
select 'B',2 union all
select 'B',3 union all
select 'B',4 union all
select 'B',5
SELECT * from @a
select 字段1,
max(case 字段2 when 1 then 字段2 end) 字段2,
max(case 字段2 when 2 then 字段2 end) 字段3,
max(case 字段2 when 3 then 字段2 end) 字段4,
max(case 字段2 when 4 then 字段2 end) 字段5,
max(case 字段2 when 5 then 字段2 end) 字段6
from @A
group by 字段1
---结果如下--------------------------------
(10 个资料列受到影响)
字段1 字段2
---- -----------
A 1
A 2
A 3
A 4
A 5
B 1
B 2
B 3
B 4
B 5
(10 个资料列受到影响)
字段1 字段2 字段3 字段4 字段5 字段6
---- ----------- ----------- ----------- ----------- -----------
A 1 2 3 4 5
B 1 2 3 4 5
(2 个资料列受到影响)
C. SQL 将横向数据转为纵向记录
使用union连接SQL语句,可以实现常见的SQL行转列运用。
以图中表格为例:
需要注意,如果有需要显示重复记录,把union 改成 union all