需要一个简单的T-SQL查询

时间:2015-08-11 16:37:22

标签: sql sql-server sql-server-2008 sql-server-2012

我有下表:

PrimaryKeyColumn1 |PrimaryKeyColumn2 |   Column_A | Column_B | Column_C|
ID1                     Key1                 0           1         0
ID2                     Key2                 1           0         1      
ID3                     Key3                 1           1         0      

基本上,我需要找出一个T-SQL查询来获得如下结果:

ID1 Key1 B
ID2 Key2 A,C
ID3 Key3 A,B

有人可以帮我解决这个问题吗?列的名称包括下划线后列名称末尾的字母(A,b,c ... z)。 0或1表示该字母是否适用于该ID。如果为0则表示不是,如果为1则表示是。所以,它必须在结果中的id旁边,如果它是1,否则如果它是0则不需要。

谢谢!

3 个答案:

答案 0 :(得分:2)

我认为最简单的方法就是使用CASE和一些字符串逻辑:

select PrimaryKeyColumn1, PrimaryKeyColumn2,
       stuff(((case when column_a = 1 then ',A' else '' end) +
              (case when column_b = 1 then ',B' else '' end) +
              (case when column_c = 1 then ',C' else '' end)
             ), 1, 1, '') as vals
from . . .

答案 1 :(得分:1)

我做过类似的事情

    CREATE TABLE #test
    (
        primaryKey nvarchar(150)
        , columnA bit
        , columnB bit
        , columnC bit
    ) -- create some test table

    INSERT INTO #test
    VALUES 
    ('ID1',1,0,0)
    ,('ID2',1,1,0)
    ,('ID3',1,0,1) -- as well as the test values

    SELECT
        *
    into #tmpUnpiv
    FROM #test
    UNPIVOT
    (
        truefalse
        for columnName in (columnA, columnB, columnC)
    ) unpiv; -- save the un-pivoted result as new table #tmpUnpiv

    SELECT
        DISTINCT
            primaryKey + ' ' + (SELECT replace(columnName,'column','') + ',' AS [text()]  from #tmpUnPiv WHERE primaryKey = p.primaryKey AND truefalse = 1 FOR XML PATH(''))
    FROM #tmpUnPiv p -- then combine results through XML PATH

    DROP TABLE #tmpUnPiv
    DROP TABLE #test
    -- drop temp tables

答案 2 :(得分:0)

尝试这样的事情(未经测试)

;with cte as
(
select *
from yourtable
cross apply (values ('A',ColumnA),
                    ('B',ColumnB),
                    ('C',ColumnC)) CS (name,value)
Where cs.value <> 0 
)
SELECT a.PrimaryKeyColumn,
       LEFT(cs.result, Len(cs.result) - 1) AS result                           
FROM   cte a
       CROSS APPLY (SELECT value + ','
                    FROM   cte B
                    WHERE  a.PrimaryKeyColumn = b.PrimaryKeyColumn
                    FOR XML PATH('')) cs (result)
GROUP  BY a.PrimaryKeyColumn,
          LEFT(cs.result, Len(cs.result) - 1)