使用SQL将类的多行排列成单行

时间:2014-11-14 04:12:59

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

我想 表名:Master_Vendors

Vendor_ID   Subvendor_id Subvendor_type Name   City State
1           abc           1              Johnny  York   MN
1           xyz           2              Meera   Birmingham NY
1           gef           3              Gaurav  Cochin NY
2           aaa           1              Laila   Lima   MA
2           bbb           2              Zebo    Reno   SC
2           ccc           3              Gina    Pitts  NY

我想要每个Vendor_ID一行,我不能使用任何聚合

Vendor_ID  Subvendor_id_1 Name_1 City_1 State_1 Subvendor_id_2 Name_2  City_2     State_2 
1           abc           Johnny  York   NY      xyz           Meera   Birmingham  NY
2           aaa           Laila    Lima  MA      bbb           Zebo    Reno        SC
由于我无法进行聚合,因此无法使用PIVOT;我以前从未使用CTE,我们可以使用CTE来实现吗?

2 个答案:

答案 0 :(得分:0)

您可以使用PIVOT功能,但仅当您使用MS SQL Server 2008或更高版本时,或者只需使用CASE WHEN语句,如下所示:

SELECT Vendor_ID    as 'Vendor_ID ',
       case when Location_ID =1 then Location_ID END as 'Location_ID_1 ' 
      ,case when City ='York' OR City ='Lima' then City END as 'City_1 ' 
      ,case when [State]='MN'  OR [State]='NA' then [State] END as 'State_1' 
      ,case when Location_ID =2 then Location_ID END as 'Location_ID_2 ' 
      ,case when City ='Birmingham' OR City ='Reno'  then City END as 'City_2 ' 
      ,case when [State]='NY' OR [State]='SC' then [State] END as 'State_2 ' 
      ,case when Location_ID =3 then Location_ID END as 'Location_ID_3 ' 
      ,case when City ='Cochin' then City END as 'City_3  ' 
      ,case when [State]='NY'  then [State] END as 'State_3 ' 
FROM Master_Vendors

答案 1 :(得分:0)

我没有把所有的字段放进去,所以你可以看到这个技术。请注意,这仅在您事先知道要在查询中显示多少个子提供时才有效:

select a.vendor_id , a.subvendor_id as Subvendor_id 1, a. Name as name_1, b.subvendor_id as Subvendor_id 2, b. Name as name_1, c.subvendor_id as Subvendor_id 3, a. Name as name_3
From Master_Vendors a
left join Master_Vendors b on a.vendor_id = b.vendor_id and  b.subvendor_type = 2
left join Master_Vendors c on a.vendor_id = c.vendor_id  and  c.subvendor_type = 3
where a.subvendor_type = 1

如果每个记录都包含所有三个subvendor,那么您可以使用内部联接。