行到列,反之亦然

时间:2016-08-25 07:24:54

标签: sql sql-server tsql unpivot

我是sql的新手,我需要一个更好的方法来处理以下情况。

enter image description here

我需要转换为以下结果。

enter image description here

3 个答案:

答案 0 :(得分:3)

执行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')) ,为每个col n 选择一个,最后选择一行SELECT而不用任何是。

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

如果唯一值为'yes'(或NULL),则最后一次选择可以作为

完成
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false" android:state_selected="true">
        <shape>
            <solid android:color="@color/lightPrimaryColor" />
        </shape>
    </item>

    <item android:state_selected="false">
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</selector>

答案 1 :(得分:3)

您可以尝试使用unpivot。以下是包含数据的示例演示。

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

答案 2 :(得分: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