如何使用sql水平写垂直表
我想像第二张图片中的示例一样制作下表
示例
我想写
答案 0 :(得分:0)
尝试
DECLARE @Sql nvarchar(max),
@DynamicColumn nvarchar(max),
@MaxDynamicColumn nvarchar(max)
SELECT @DynamicColumn = STUFF((SELECT DISTINCT', '+QUOTENAME(CAST(Col1 AS VARCHAR(50)))
FROM #Temp FOR XML PATH ('')),1,1,'')
SELECT @DynamicColumn
SET @Sql='SELECT '+ @DynamicColumn+'
FROM
(
SELECT *
FROM #Temp o
)AS src
PIVOT
(
MAX(Col2) FOR [Col1] IN ('+@DynamicColumn+')
) AS Pvt
'
EXEC (@Sql)
PRINT @Sql
答案 1 :(得分:0)
嗨,如果您了解您的查询,我认为该查询可以帮助您获得例外结果:
CREATE TABLE #TEMP (colName varchar(250), colOther varchar(250))
INSERT INTO #TEMP
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK'
select Desen,Ebat,ZeminRengi
from #TEMP
PIVOT (
MAX(colOther)
FOR colName IN (Desen,Ebat,ZeminRengi)) AS Pvt
DROP TABLE #TEMP
查看其他链接和google: Understanding PIVOT function in T-SQL MSDN Google- search