每个外键组合多个记录

时间:2015-01-07 16:35:05

标签: sql sql-server-2008 cross-apply

我有一个有点棘手的表结构,它继承了遗产方式。

我有一张大约有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'

2 个答案:

答案 0 :(得分:1)

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

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;

答案 1 :(得分:1)

您也可以使用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