2016-08-15 9 views
2

안녕하세요. 예제 코드와 원하는 결과가 있습니다. 피벗 및 왼쪽에 동일한 테이블을 결합하고 비슷한 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 
---------------------------------------------------------- 
+1

다른 제품에는 피벗 기능이 다릅니다. 사용중인 dbms에 태그를 지정하십시오! – jarlh

+0

죄송합니다. SQL Server를 사용하고 있습니다. – frar

+1

당신은'PIVOT' 연산자에 대해 살펴 보셨습니까? – Squirrel

답변

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 
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'[email protected]+' 
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 
+1

COUNT 개 (유형)이면 충분합니다. 추가 열이 필요하지 않습니다. – Serg

+0

@Serg Thanks! 나는 동의한다! 답변의이 부분을 변경했습니다. – gofr1

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 
관련 문제