根据表中的列创建新列

时间:2016-10-11 21:11:12

标签: sql-server tsql

我在下面的例子中有代码。

    legacy_id  f_phone_number_1 b_phone_number_1 f_phone_number_2
         1      1234567890        1233854100        4110256565
         2      0707070770        7895120044

我希望数据最终如下所示。

    Select fill.legacy_id, max(fill.f_phone_number_1),max(fill.b_phone_number_1),max(fill.f_phone_number_2)
    from
    (
      Select
           a.legacy_id as legacy_id, a.phone_type as phone_type,
           case
               when a.phone_type = 'F' then a.phone_number and 
               dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 1
               else null
           end as f_phone_number_1,
           case
               when a.phone_type = 'F' then a.phone_number and
               dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 2
               else null
           end as f_phone_number_2,
           case
               when a.phone_type = 'b' then a.phone_number and
               dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 1
               else null
           end as b_phone_number_1
      from table a
      group by a.legacy_id, a.phone_type, a.phone_number
    ) fill
    group by fill.legacy_id

我的初步方法有效,但我希望有更高效的方法。

SELECT COUNT(influencers.*, fi.id) AS has_relation FROM "inf...

是否有更有效的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果你不需要动态,那么条件聚合应该可以做到这一点

Declare @YourTable table (legacy_id int,phone_type varchar(25),phone_number varchar(25))
Insert Into @YourTable values
(1,'f','1234567890'),
(1,'b','1233854100'),
(1,'f','4110256565'),
(2,'f','0707070770'),
(2,'b','7895120044')

Select legacy_id
      ,f_phone_number_1 = max(case when phone_type='f' and RowNr=1 Then phone_number else '' end)
      ,b_phone_number_1 = max(case when phone_type='b' and RowNr=1 Then phone_number else '' end)
      ,f_phone_number_2 = max(case when phone_type='f' and RowNr=2 Then phone_number else '' end)
      ,b_phone_number_2 = max(case when phone_type='b' and RowNr=2 Then phone_number else '' end)
 From (
        Select *
              ,RowNr=Row_Number() over (Partition By legacy_id,phone_type Order By (Select NULL) ) 
         From  @YourTable 
      ) A
 Group By legacy_id

返回

legacy_id   f_phone_number_1    b_phone_number_1    f_phone_number_2    b_phone_number_2
1           4110256565          1233854100          1234567890  
2           0707070770          7895120044