2014-11-25 209 views
1

我有下表中的詳細信息,如下例所示。動態數據透視表

表:測試

create table test 
(
cola varchar(10), 
colb varchar(10), 
colc varchar(10) 
); 

插入

insert into test values('111','222','A1'); 
insert into test values('111','333','A2'); 
insert into test values('111','344','A3'); 
insert into test values('111','444','A4'); 
insert into test values('767','222','A1'); 
insert into test values('767','333','A2'); 
insert into test values('767','344','A3'); 
insert into test values('5443','555','B1'); 
insert into tft values('8998','222','A1'); 
insert into tft values('8998','333','A2');  
insert into tft values('8998','353','A8'); 
insert into test values('5443','555','B1'); 

注意:現在我只想顯示的記錄中, cola屬於colc的值A1,A2,A3

預期結果的

場景:1

IF @Stuff = A1,A2,A3

然後,結果應該是:

cola A1 A2 A3 
------------------ 
767 1 1 1 

備註:在上述結果中,111未出現,因爲它也屬於A4

場景:2

IF @Stuff = A1,A2,A8

然後,結果應該是:

cola A1 A2 A8 
------------------ 
8998 1 1 1 

:在上面的結果767不是因爲出現它屬於A3而不是A8

場景:3

IF @Stuff = A1,A2,A3,A4

然後,結果應該是:

cola A1 A2 A3 A4 
--------------------- 
111 1 1 1 1 

:在上面的結果的準確111屬於A1,A2,A3,A4

方案:4

IF @Stuff = B1

然後,結果應該是:

cola B1 
---------- 
5443 2 

:在上面的結果中5443時,會出現2次與B1

嘗試:

透視查詢

DECLARE @Stuff varchar(max) = 'A1,A2,A3' 
DECLARE @Sql varchar(max) 

SET @Sql = 'SELECT cola,' [email protected]+ ' 
      from 
      (
       select cola,colc 
       from test 
      )p 
      PIVOT 
      (
       COUNT(colc) 
       FOR colc IN ('[email protected]+') 
      )AS pvt' 

PRINT(@Sql) 
EXEC(@Sql)  

獲取結果

cola A1 A2 A3 
------------------- 
111  1 1 1 
5443 0 0 0 
767  1 1 1 
8998 1 1 0 

回答

2

它是一個不同的問題與this

DECLARE @Stuff varchar(max) = 'A1,A2,A3' 
     DECLARE @Sql varchar(max) 
DECLARE @totalparam varchar(max) = len(@Stuff) - len(replace(@Stuff,',',''))+1 
DECLARE @colcList varchar(max) = REPLACE(@Stuff,',',''',''') 
     SET @Sql = 'SELECT cola,' [email protected]+ ' 
        FROM 
        (SELECT a.cola, a.colc from test a JOIN (
         SELECT cola, COUNT(InList) AS InList, COUNT(TOTAL) AS TOTAL FROM (
           SELECT cola, 
            CASE WHEN colc IN ('''[email protected]+''') THEN 
             1 
             END AS InList, 
             1 AS TOTAL FROM test 
           group by cola, colc) AS tester group by cola) b ON a.cola = b.cola 
         WHERE b.TOTAL = '[email protected]+' AND b.InList = b.TOTAL 
         )p 
       PIVOT 
       (
        COUNT(colc) 
        FOR colc IN ('[email protected]+') 
       )AS pvt' 
    PRINT(@colcList) 
    PRINT(@Sql) 
    EXEC(@Sql) 
+0

太棒了!非常感謝。 – MAK 2014-11-25 13:27:26