每个外键合并多条记录

Combine Multiple records per Foreign Key

我有一个有点棘手的 table 结构,它继承自 way legacy。

我有一个 table 大约有 4 列重要。

 DayNight    Cust_Code    Name     Phone     Counter
   D          ABC0111    Marty    aaaaa        1 
   D          ABC0111    John     bbbbb        2 
   D          ABC0111    Beth     ccccc        3 
   N          ABC0111    Sue      ddddd        1 
   N          ABC0111    Mary     eeeee        2 

我需要将这5条记录合并成一行,结构如下。

CustCode,     Day1,      Day2,      Day3,      Night1,      Night2,      Night3
ABC0111,   Marty aaaaa, John bbbbb, Beth ccccc, Sue ddddd , Mary eeeee,    null or ''

我试过的

SELECT DISTINCT
  x.NAME,
  x.DAYNIGHT,
  x.PHONE,
  x.COUNTER,
   cp.NAME,
   cp.DAYNIGHT,
   cp.COUNTER,
   cp.PHONE,
   cp.POSITION
        FROM (
               SELECT *
               from table1 where
               table1.DAYNIGHT LIKE 'N'
             ) x
     join  table1 t1 on t1.CUST_CODE = x.CUST_CODE 
     where cp.DAYNIGHT LIKE 'D'

我倾向于使用条件聚合来做到这一点:

select CustCode,
       max(case when DayNight = 'D' and Counter = 1 then Name + ' ' + Phone end) as Day1,
       max(case when DayNight = 'D' and Counter = 2 then Name + ' ' + Phone end) as Day2,
       max(case when DayNight = 'D' and Counter = 3 then Name + ' ' + Phone end) as Day3,
       max(case when DayNight = 'N' and Counter = 1 then Name + ' ' + Phone end) as Night1,
       max(case when DayNight = 'N' and Counter = 2 then Name + ' ' + Phone end) as Night2,
       max(case when DayNight = 'N' and Counter = 3 then Name + ' ' + Phone end) as Night3
from table1
group by CustCode;

你也可以使用Pivot

SELECT *
FROM  (SELECT cust_code,
              NAME + ' ' + phone                                                                  AS pp,
              CASE WHEN daynight ='D' THEN 'Day' ELSE 'Night' END + CONVERT(VARCHAR(30), counter) AS rr
       FROM   tablename)a
      PIVOT (Max(pp)
            FOR rr IN([Day1],
                      [Day2],
                      [Day3],
                      [Night1],
                      [Night2],
                      [Night3])) pv