2013-02-15 205 views
0
Job Batch id Company Outlet Id Clearance required Hanky required 
1    10     T     T 

現在我想下面樞軸查詢援助

Job Batch id Company Outlet ID Reason  
1    10     Clearance Required , Hanky Required 

我的大腦已經凍結,爲需要幫助?

如何構建此unpivot查詢?

回答

1

在這裏你去 - 只要你結合像這樣的列。我正在用STUFF刪除開頭的逗號:

select JobBatchId, 
    CompanyOutletId, 
    STUFF(
    ISNULL(CASE WHEN ClearanceRequired = 'T' THEN ',Clearance Required' END, '') + 
    ISNULL(CASE WHEN HankyRequired = 'T' THEN ',Hanky Required' END, '') 
    , 1, 1, '') Reasons 
from YourTable 

SQL Fiddle

1

我建議不要把你的SQL查詢單個列(Reason)內的多個值,而是留下多達表示層,如果這就是你想看到的數據...

但這裏是你如何可以在SQL做到這一點:

SELECT 
    [Job Batch Id], 
    [Company Outlet Id], 
    CASE 
     WHEN [Clearance Required] = 'T' 
     THEN 'Clearance Required' 
     ELSE '' END + 
    -- Determine if the comma is needed or not... 
    CASE 
     WHEN [Clearance Required] = 'T' 
      AND [Hanky Required] = 'T' 
     THEN ' , ' 
     ELSE '' END + 
    CASE 
     WHEN [Hanky Required] = 'T' 
     THEN 'Hanky Required' 
     ELSE '' END AS Reason 
FROM YourTable 
1

嘗試:

select [Job Batch id], [Company Outlet Id], 
     case [Clearance required] 
      when 'T' then 'Clearance Required' + 
       case [Hanky required] when 'T' then ' , ' else '' end 
     else '' 
     end + case [Hanky required] when 'T' then 'Hanky Required' else '' end as [Reason] 
from theTable 
1

您可以使用UNPIVOTCROSS APPLYFOR XML PATH得到結果:

;with cte as 
(
    select [Job Batch id], [Company Outlet Id], 
    col, value 
    from yourtable 
    unpivot 
    (
    value 
    for col in ([Clearance required], [Hanky required]) 
) unpiv 
) 
select distinct t1.[Job Batch id], 
    t1.[Company Outlet Id], 
    left(s.reason, len(s.reason)-1) reason 
from cte t1 
cross apply 
(
    select t2.col + ', ' 
    FROM cte t2 
    where t1.[Job Batch id] = t2.[Job Batch id] 
    and t1.[Company Outlet Id] = t2.[Company Outlet Id] 
    FOR XML PATH('') 
) s (reason) 

SQL Fiddle with Demo

或者你可以使用UNPIVOTSTUFFFOR XML PATH

;with cte as 
(
    select [Job Batch id], [Company Outlet Id], 
    col, value 
    from yourtable 
    unpivot 
    (
    value 
    for col in ([Clearance required], [Hanky required]) 
) unpiv 
) 
select distinct t1.[Job Batch id], 
    t1.[Company Outlet Id], 
    STUFF(
     (SELECT ', ' + col 
      FROM cte t2 
      where t1.[Job Batch id] = t2.[Job Batch id] 
      and t1.[Company Outlet Id] = t2.[Company Outlet Id] 
      FOR XML PATH ('')) 
      , 1, 1, '') AS Reason 
from cte t1 

SQL Fiddle with Demo