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;
相关文章