這是無關的MAX,因爲你可以使用旋轉+ STUFF與FOR XML PATH:
SELECT *
FROM (
SELECT DISTINCT t.EmpID,
t.[Year],
STUFF((
SELECT '-'+Remark
FROM YourTable
WHERE t.EmpID = EmpID AND t.[Year] = [Year]
FOR XML PATH('')
),1,1,'') Remark
FROM YourTable t
) as d
PIVOT (
MAX(Remark) FOR [Year] IN ([2010],[2014],[2015],[2016])
) as pvt
在d
部分您將獲得:
EmpID Year Remark
1 2010 Poor
1 2014 Good
1 2015 Very Good
1 2016 Normal-Good-Well
STUFF
用於去除第一-
,
用於從行使值作爲1行
FOR XML PATH
,
PIVOT
到行轉換成列
輸出:
EmpID 2010 2014 2015 2016
1 Poor Good Very Good Normal-Good-Well
EDIT#1
與MAX的另一種方式和CASE WHEN(相同的輸出):
SELECT EmpID,
MAX(CASE WHEN [Year] = 2010 THEN Remark END) as [2010],
MAX(CASE WHEN [Year] = 2014 THEN Remark END) as [2014],
MAX(CASE WHEN [Year] = 2015 THEN Remark END) as [2015],
MAX(CASE WHEN [Year] = 2016 THEN Remark END) as [2016]
FROM (
SELECT DISTINCT t.EmpID,
t.[Year],
STUFF((
SELECT '-'+Remark
FROM YourTable
WHERE t.EmpID = EmpID AND t.[Year] = [Year]
FOR XML PATH('')
),1,1,'') Remark
FROM YourTable t
) as d
GROUP BY EmpID
編輯#2
動態SQL:
DECLARE @sql nvarchar(max),
@col nvarchar(max)
SELECT @col = (
SELECT DISTINCT ','+QUOTENAME([Year])
FROM YourTable
FOR XML PATH('')
)
SELECT @sql = N'
SELECT *
FROM (
SELECT DISTINCT t.EmpID,
t.[Year],
STUFF((
SELECT ''-''+Remark
FROM YourTable
WHERE t.EmpID = EmpID AND t.[Year] = [Year]
FOR XML PATH('''')
),1,1,'''') Remark
FROM YourTable t
) as d
PIVOT (
MAX(Remark) FOR [Year] IN ('+STUFF(@col,1,1,'')+')
) as pvt'
EXEC sp_executesql @sql
你想一年列是動態或靜態的? –
我已經得到這個動態使用不同的一年查詢但那不是問題 – Pravin