我有一个临时表#reservationWithBranch contains
ScheduleName UserId BranchId BranchCode
NULL NULL 1 TVM
XMS DAJ 20 Dec 2014 5 2 EKM
XMS DAJ 20 Dec 2014 5 2 EKM
XMS DAJ 29 Dec 2014 5 2 EKM
XMS DAJ 29 Dec 2014 5 2 EKM
NULL 2 3 KDK
XMS DAJ 29 Dec 2014 6 3 KDK
XMS DAJ 20 Dec 2014 6 3 KDK
NULL 8 3 KDK
NULL 1 15 PLK
NULL 7 15 PLK
NULL NULL 16 KNR
NULL 9 17 KA
ScheduleName,UserId,BranchId和BranchCode是动态的我想得到如下输出
SheduleName TVM EKM KDK PLK KNR KAK
DAJ 20 Dec 2014 0 2 1 0 0 0
DAJ 29 Dec 2014 0 2 1 0 0 0
我尝试了以下代码
SELECT * from #reservationWithBranch
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT ScheduleName, ' + @ColumnName + '
FROM #reservationWithBranch
PIVOT(COUNT(ScheduleName)
FOR BranchCode IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
print @DynamicPivotQuery
DROP TABLE #reservationWithBranch
但结果不正确。任何人都可以帮助我吗?
答案 0 :(得分:1)
首先,我发现你的表中有相同的数据。为了避免这种情况并获得实际计数,请插入新表
SELECT DISTINCT *,
CASE WHEN ScheduleName IS NULL THEN NULL ELSE COUNT(BranchCode) OVER(PARTITION BY ScheduleName,BranchCode) END CNT
INTO #TEMP2
FROM #TEMP
获取列
DECLARE @cols NVARCHAR (MAX)
DECLARE @Columns2 NVARCHAR (MAX)
SET @cols = SUBSTRING((SELECT DISTINCT ',['+BranchCode+']' FROM #TEMP2 GROUP BY BranchCode FOR XML PATH('')),2,8000)
SET @Columns2 = SUBSTRING((SELECT DISTINCT ',ISNULL(['+BranchCode+'],0) AS ['+BranchCode+']' FROM #TEMP2 GROUP BY BranchCode FOR XML PATH('')),2,8000)
然后动态转动
DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT ScheduleName,' + @Columns2 + ' FROM
(
SELECT ScheduleName,BranchCode,CNT FROM #TEMP2
) x
PIVOT
(
SUM(CNT)
FOR [BranchCode] IN (' + @cols + ')
) p
WHERE ScheduleName IS NOT NULL;'
EXEC SP_EXECUTESQL @query
这是你的结果