本文介紹了SQL Server中的高級行到列轉換(透視表)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有這個表:
---------------------------------------
| Id | worker | workStation | amount
---------------------------------------
| 1 | John | Suspension | 5
| 2 | John | Wheels | 8
| 3 | Peter | Wheels | 1
| 4 | Peter | Engines | 2
---------------------------------------
我需要顯示以下內容的查詢:
-------------------------------------------
| worker | Suspension | Wheels | Engines
-------------------------------------------
| John | 5 | 8 | NULL
| Peter | NULL | 1 | 2
-------------------------------------------
借助
Efficiently convert rows to columns in sql server和
https://docs.microsoft.com/es-es/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15(主要是第一個)我做到了:
---------------------------------
| Suspension | Wheels| Engines
---------------------------------
| 5 | 8 | NULL
| NULL | 1 | 2
---------------------------------
這幾乎就是我所需要的,但我仍然缺少了解工作人員名稱的列。
我需要使用未知數量的工作站來透視查詢。
我的代碼是:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(workStation)
FROM TableName
group by workStation
ORDER BY workStation
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
SELECT amount, worker, workStation
FROM TableName
) x
pivot
(
max(amount)
for workStationin (' + @cols + N')
) p '
exec sp_executesql @query;
我如何才能找到這一缺失的列?
提前感謝您。
推薦答案
您可以選擇工作人員,如果不想重復行,可以按工作人員分組
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(workStation)
FROM TableName
group by workStation
ORDER BY workStation
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT worker,' + @cols + N' from
(
SELECT amount, worker, workStation
FROM TableName
) x
pivot
(
max(amount)
for workStationin (' + @cols + N')
) p '
exec sp_executesql @query;
這篇關于SQL Server中的高級行到列轉換(透視表)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,