2014-04-30 117 views
1

我面臨着相當令人頭疼的問題。在查詢中合併記錄的列

我有一張表,結構如下。

coursename - day1 - moment1 - day2 - moment2 - day3 - moment3 - day4 - moment4 
course A - mon - morning - wed - afternoon - NULL - NULL  - NULL - NULL 
course B - tue - evening - thu - evening - NULL - NULL  - NULL - NULL 
course C - mon - evening - tue - evening - wed - morning - thu - evening 
course D - wed - morning - thu - morning - sat - afternoon- NULL - NULL 

輸出應該

coursename - timetable 
course A - mon morning, wed afternoon 
course B - tue/thu evening 
course C - mon/tue/thu evening, wed morning 
course D - wed/thu morning, sat afternoon 

我將如何去查詢類似的東西?我唯一能想到的就是使用嵌套的情況,但是恐怕會殺死性能。

我使用MS SQL Server 2012的

+0

老實說,我會在前端做格式化,讓數據庫做它擅長的。然而,這就是說,你可能會用它來標準化你的桌子,這會讓生活更輕鬆。 –

回答

1

如果我們有很好的字符串聚合函數,這可能是更漂亮,但只給你一個想法:

with cte as (
-- unpivot days into strings 
     select 
      T.coursename, A.day, A.moment 
     from Table1 as T 
      outer apply (values 
        (T.day1, T.moment1), 
        (T.day2, T.moment2), 
        (T.day3, T.moment3), 
        (T.day4, T.moment4) 
      ) as A(day, moment) 
), cte2 as (
-- concat all days for each moment 
    select 
     c.coursename, c.moment, 
     stuff(
     (
      select '/' + t.day 
      from cte as t 
      where t.coursename = c.coursename and t.moment = c.moment 
      for xml path(''), type 
     ).value('.', 'nvarchar(max)') 
     ,1,1,'') as days 
    from cte as c 
    group by c.coursename, c.moment 
) 
-- concat final timetable 
select 
    c.coursename, 
    stuff(
     (
     select ', ' + t.days + ' ' + t.moment 
     from cte2 as t 
     where t.coursename = c.coursename 
     for xml path(''), type 
     ).value('.', 'nvarchar(max)') 
    ,1,2,'') as timetable 
from cte2 as c 
group by c.coursename 

sql fiddle demo

+1

Knocks忽略了我正在研究的'COALESCE'想法。先生,先生! –