您好我有一个示例代码和所需的结果,我试图使用 Pivot和左连接相同的表,看着类似的q在这里,但我没有得到我想要的结果所以我要求专家的帮助:):
DECLARE @temp TABLE (id INT, typeID INT)
INSERT INTO @temp VALUES(1,1)
INSERT INTO @temp VALUES(1,2)
INSERT INTO @temp VALUES(1,3)
INSERT INTO @temp VALUES(1,4)
INSERT INTO @temp VALUES(1,5)
INSERT INTO @temp VALUES(2,1)
INSERT INTO @temp VALUES(2,2)
INSERT INTO @temp VALUES(2,3)
INSERT INTO @temp VALUES(3,5)
SELECT * FROM @temp
--desired result
----------------------------------------------------------
[id] [typeID1] [typeID2] [typeID3] [typeID4] [typeID5]
1 1 1 1 1 1
2 1 1 1
3 1
----------------------------------------------------------
答案 0 :(得分:1)
此代码将在大多数SQL DBMS上运行。
select id,
max(case typeID when 1 then 1 end) as typeID1,
max(case typeID when 2 then 1 end) as typeID2,
max(case typeID when 3 then 1 end) as typeID3,
max(case typeID when 4 then 1 end) as typeID4,
max(case typeID when 5 then 1 end) as typeID5
from @temp
group by id
答案 1 :(得分:0)
PIVOT和动态SQL的另一种方式(因为我们不知道表中有多少typeID
:
USE tempdb
CREATE TABLE #temp (id INT, typeID INT)
INSERT INTO #temp VALUES
(1,1),(1,2),(1,3),(1,4),(1,5),(2,1),(2,2),(2,3),(3,5)
DECLARE @columns nvarchar(max),
@sql nvarchar(max)
SELECT @columns = COALESCE(@columns,'') + ',[typeID'+CAST(typeID as nvarchar(max))+']'
FROM #temp
GROUP BY typeID
SET @sql = N'
SELECT id'+@columns+'
FROM (
SELECT ''typeID''+CAST(typeID as nvarchar(max)) as [types],
id
FROM #temp) as t
PIVOT (
COUNT([types]) FOR [types] IN ('+STUFF(@columns,1,1,'')+')
) as unpvt'
EXEC sp_executesql @sql
DROP TABLE #temp
输出:
id typeID1 typeID2 typeID3 typeID4 typeID5
1 1 1 1 1 1
2 1 1 1 0 0
3 0 0 0 0 1
答案 2 :(得分:0)
请遵循:https://msdn.microsoft.com/en-us/library/hh231515.aspx
在我看来,如果你了解它的行为方式,那将非常有用:
DECLARE @temp TABLE (id INT, typeID INT)
INSERT INTO @temp VALUES(1,1)
INSERT INTO @temp VALUES(1,2)
INSERT INTO @temp VALUES(1,3)
INSERT INTO @temp VALUES(1,4)
INSERT INTO @temp VALUES(1,5)
INSERT INTO @temp VALUES(2,1)
INSERT INTO @temp VALUES(2,2)
INSERT INTO @temp VALUES(2,3)
INSERT INTO @temp VALUES(3,5)
SELECT ID,
[1] as Type1, [2] as Type2, [3] as Type3, [4] as Type4, [5] as Type5
FROM
(SELECT ID, typeID
FROM @temp) AS SourceTable
PIVOT
(
COUNT(TYPEID)
FOR TYPEID IN ([1], [2], [3], [4],[5])
) AS PivotTable