SQL将行中的多个值返回到列中

时间:2015-06-24 20:49:00

标签: sql sql-server database

我有一个包含几列的表格,但只有两列与此搜索相关:

ITEMNMBR和ALTITEM1

现在数据显示如下

ITEMNMBR    ALTITEM1
A0001       ABCDEF
A0001       GBESJF
A0001       SDFJLK
B0001       JKHKJF
C0001       KLJSDF
C0001       MSXNCV

我想显示数据,因此列中只显示每个ITEMNMBR的一个实例,相应的ALTITEM1值出现在新列中。

ITEMNMBR    ALTITEM_1    ALTITEM_2    ALTITEM_3
A0001       ABCDEF       GBESJF       SDFJLK
B0001       JKHKJF
C0001       KLJSDF       MSXNCV

每个ITEMNMBR最多可包含20个ALTITEM1值。如果可能的话,动态地添加这些列很棒,但我认为它们需要在代码中进行配置...

SQL server 2008 R2

2 个答案:

答案 0 :(得分:0)

    (select itemnmber,
    case when altitem1 as altitem_1,
    null as altitem_2,
    null as altitem_3
    --repeat this until you reach 20 items
    from tablename)
    union all
    (select itemnmber,
    null as altitem_1,
    altitem1 as altitem_2,
    null as altitem_3
    --repeat this until you reach 20 items
    from tablename) 
     union all
    (select itemnmber,
    null as altitem_1,
    null as altitem_2,
    altitem1 as altitem_3,
    --repeat this until you reach 20 items
    from tablename)
    ---repeat the whole process as many times with the column names 

您也可以使用空字符串而不是null

答案 1 :(得分:0)

您只需使用PIVOT功能,如下所示:

-- Create demo data
CREATE TABLE #temp(ITEMNMBR nvarchar(20), ALTITEM1 nvarchar(20))

INSERT INTO #temp(ITEMNMBR, ALTITEM1)
VALUES  (N'A0001',N'ABCDEF'),(N'A0001',N'GBESJF'),
        (N'A0001',N'SDFJLK'),(N'B0001',N'JKHKJF'),
        (N'C0001',N'KLJSDF'),(N'C0001',N'MSXNCV')

SELECT *
FROM (
    SELECT ITEMNMBR, ALTITEM1, ROW_NUMBER() OVER(PARTITION BY ITEMNMBR ORDER BY ALTITEM1) as rowNo
    FROM #temp
    ) as data
PIVOT(
    MAX(ALTITEM1)
    FOR rowNo IN([1],[2],[3])
) as pvt

-- Cleanup
DROP TABLE #temp

如果您需要更加动态的方法(在视图中无法工作),您还可以在此处查看我的其他解决方案,它将动态创建IN() - 子句{{3 }}