[英]How to use values from one table as column names in a new Table in SQL SERVER?
I have a table that looks like this:我有一个看起来像这样的表:
EmployeeName![]() |
City![]() |
---|---|
Maria![]() |
Chicago![]() |
John![]() |
Chicago![]() |
Anna![]() |
LA![]() |
Peter![]() |
LA![]() |
Carrie![]() |
NYC![]() |
And I need to create a table that will look like this:我需要创建一个如下所示的表:
Chicago![]() |
LA![]() |
NYC![]() |
---|---|---|
Maria![]() |
Anna![]() |
Carrie![]() |
John![]() |
Peter![]() |
I found this我找到了这个
SELECT (ColumnNames)
FROM (TableName)
PIVOT
(
AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias);
But I am confused which aggregate function to use since the values are not numeric and also my table has too many Cities to write them manually.但是我很困惑要使用哪个聚合 function,因为这些值不是数字,而且我的表中有太多城市无法手动写入。
You can PIVOT with the addition of a new column.您可以添加一个新列 PIVOT。 In this simple case I used the window function
dense_rank() over()
在这个简单的例子中,我使用了 window function
dense_rank() over()
Results结果
Declare @YourTable Table ([EmployeeName] varchar(50),[City] varchar(50)) Insert Into @YourTable Values
('Maria','Chicago')
,('John','Chicago')
,('Anna','LA')
,('Peter','LA')
,('Carrie','NYC')
Select *
From (
Select EmployeeName
,City
,RN = dense_rank() over (partition by city order by EmployeeName desc)
From @YourTable
) src
Pivot ( max(EmployeeName) for City in ( [Chicago],[LA],[NYC]) )pvt
Results结果
RN Chicago LA NYC
1 Maria Peter Carrie
2 John Anna NULL
UPDATE- Dynamic Approach更新-动态方法
Declare @SQL varchar(max) = '
Select *
From (
Select EmployeeName
,City
,RN = dense_rank() over (partition by city order by EmployeeName desc)
From YourTable
) src
Pivot ( max(EmployeeName) for City in ( '+ (Select string_agg(quotename(City),',') From (Select distinct City from YourTable) A) +' ) )pvt
'
Exec(@SQL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.