2016-08-25 7 views
0

私はSQLにとって非常に新しいので、以下のシナリオではより良いアプローチが必要です。SQLの行と逆行

enter image description here

そして、私は以下の結果に変換する必要があります。

enter image description here

+1

colion-col4ごとに1つ選択します。 – jarlh

答えて

3

あなたがアンピボットを使用して試すことができます。ここにデモのサンプルデータを示します。

DECLARE @Table TABLE (
     ID INT 
     ,COL1 VARCHAR(3) 
     ,COL2 VARCHAR(3) 
     ,COL3 VARCHAR(3) 
     ,COL4 VARCHAR(3) 
     ) 
INSERT INTO @TABLE VALUES 

(1,'yes',null,'yes',null) 
,(2,null,'yes',null,'yes') 
,(3,null,null,'yes',null) 
,(4,null,null,null,null) 
,(5,null,'yes','yes',null) 
,(6,null,null,null,null) 
,(7,null,null,null,'yes') 


SELECT id 
    ,yes 
FROM (
    SELECT id 
     ,col1 
     ,col2 
     ,col3 
     ,col4 
    FROM @TABLE 
    where coalesce(col1, col2, col3, col4) is not null 
    ) AS cp 
UNPIVOT(yes FOR col IN (
      col1 
      ,col2 
      ,col3 
      ,col4 
      )) AS up 
union 
select id, null from @TABLE 
    where coalesce(col1, col2, col3, col4) is null 
order by id 
3

UNION ALLを行い、1は各COL のnを選択し、最後に一つはどのはい、まったくせずに行に対してSELECT。

select id, 'col1' from tablename where col1 = 'yes' 
union all 
select id, 'col2' from tablename where col2 = 'yes' 
union all 
select id, 'col3' from tablename where col3 = 'yes' 
union all 
select id, 'col4' from tablename where col4 = 'yes' 
union all 
select id, cast(null as char(4)) from tablename 
    where 'yes' not in (coalesce(col1, 'x'), 
         coalesce(col2, 'x'), 
         coalesce(col3, 'x'), 
         coalesce(col4, 'x')) 

のみ値が「はい」(またはNULL)の場合、最後の選択は、あなたが以下のようにそれを行うことができ、また

select id, cast(null as char(4)) from tablename 
where coalesce(col1, col2, col3, col4) is null 
+0

私はこのキャストが必要とは思わない。 – sagi

+2

col1、col2などのNULL値はどうですか? 'NOT IN(col1、col2 ..)が問題になるのではないでしょうか? –

+0

@RaduGheorghiu、おっと、私には恥...あなたは絶対に正しいです。編集します。 – jarlh

1

として行うことができます。

;WITH CTE 
AS 
(
    SELECT 
     B.ID, 
     B.yes, 
     B.col 
    FROM 
     (SELECT ID , 
       ISNULL(COL1, '') COL1 , 
       ISNULL(COL2, '') COL2, 
       ISNULL(COL3, '') COL3 , 
       ISNULL(COL4, '') COL4 
      FROM @Tbl) A 
    UNPIVOT 
    (
     col 
     FOR yes in (col1, col2, col3, col4) 
    ) B 
) 


SELECT CTE.ID, CTE.yes FROM CTE 
WHERE col = 'yes' 
UNION ALL 
SELECT DISTINCT ID, '' FROM CTE A 
WHERE NOT EXISTS 
(
    SELECT 1 FROM CTE B WHERE 
     B.ID = A.ID AND 
     B.col = 'yes' 
) 

結果:

ID   yes 
----------- ----- 
1   COL1 
1   COL3 
2   COL2 
2   COL4 
3   COL3 
4   
5   COL2 
5   COL3 
6   
7   COL4 
+0

これは 'yes'値を持つ行を除外します。 –