[英]Update SQL Server table values in one table based upon values in another table that relate to the column names in the first
[英]How to use values from one table as column names in a new Table in SQL SERVER?
我有一個看起來像這樣的表:
員工姓名 | 城市 |
---|---|
瑪麗亞 | 芝加哥 |
約翰 | 芝加哥 |
安娜 | 洛杉磯 |
彼得 | 洛杉磯 |
嘉莉 | 紐約市 |
我需要創建一個如下所示的表:
芝加哥 | 洛杉磯 | 紐約市 |
---|---|---|
瑪麗亞 | 安娜 | 嘉莉 |
約翰 | 彼得 |
我找到了這個
SELECT (ColumnNames)
FROM (TableName)
PIVOT
(
AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias);
但是我很困惑要使用哪個聚合 function,因為這些值不是數字,而且我的表中有太多城市無法手動寫入。
您可以添加一個新列 PIVOT。 在這個簡單的例子中,我使用了 window function dense_rank() over()
結果
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
結果
RN Chicago LA NYC
1 Maria Peter Carrie
2 John Anna NULL
更新-動態方法
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.