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