SQL查询使用不同的行来创建不同的行

时间:2015-08-31 21:09:21

标签: mysql sql sql-server sql-server-2012

以下是我在查询的表格中的数据

表1

ITEM     SEQUENCE     CODE
Item1       1            A 
Item1       2            B
Item2       1            B
Item2       2            C
Item2       3            D

我当前的查询看起来像

  Select Distinct Table1.ITEM, 
  case when Table1.SEQUENCE = '1' Then Table2.DSC end As FirstDSC,
  Case When Table1.SEQUENCE = '2' then Table2.DSC End As SecondDSC,
  Case When Table1.SEQUENCE = '3' Then Table2.DSC End As ThirdDSC
    From Table1
    Join Table2 on Table2.Code = Table1.Code
    Where Table1.Item In (Subquery here to find distinct values that Item can be)

它目前返回的数据类似于

ITEM  FIRSTDSC SECONDDSC THIRDDSC
Item1   DSC-A     NULL      NULL
Item1   NULL     DSC-B      NULL 

我想知道如何使数据返回看起来像

ITEM FIRSTDSC  SECONDDSC  THIRDDSC
Item1  DSC-A      DSC-B       NULL
Item2  DSC-B      DSC-C       DSC-D

有没有一种好的方法可以做到这一点,或者我目前的查询方向是否完全错误?

1 个答案:

答案 0 :(得分:3)

我认为你想要group by和条件聚合,而不是distinct

Select Table1.ITEM, 
       max(case when Table1.SEQUENCE = '1' Then Table2.DSC end) As FirstDSC,
       max(Case When Table1.SEQUENCE = '2' then Table2.DSC End) As SecondDSC,
       max(Case When Table1.SEQUENCE = '3' Then Table2.DSC End) As ThirdDSC
From Table1 Join
     Table2
     on Table2.Code = Table1.Code
Where Table1.Item In (Subquery here to find distinct values that Item can be)
group by table1.ITEM;