使用多列将重复行合并为一行

时间:2015-12-30 21:57:38

标签: sql merge sql-server-2012 duplicates

我想知道如何获取看起来像这样的数据集:

表1:

RecordID    Code
A   351
A   352
A   353
A   354

看起来像这样:

表2:

您已经可以假设我使用我在下面创建的列标题创建了第二个表

RecordID    351 352 353 354 355 356
   A         Y   Y   Y   Y   N   N

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

SELECT RecordID,
    CASE WHEN SUM(CASE WHEN Code = 351 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [351],
    CASE WHEN SUM(CASE WHEN Code = 352 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [352],
    CASE WHEN SUM(CASE WHEN Code = 353 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [353],
    CASE WHEN SUM(CASE WHEN Code = 354 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [354],
    CASE WHEN SUM(CASE WHEN Code = 355 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [355],
    CASE WHEN SUM(CASE WHEN Code = 356 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [356]
FROM yourTable
GROUP BY RecordID

答案 1 :(得分:0)

你可以尝试这样的事情:

select
    RecordID,
    iif(sum(iif([Code]=351,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=352,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=353,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=354,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=355,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=356,1,0))>0,'Y','N')
from table
group by RecordID