透视查询帮助

时间:2013-02-15 15:19:09

标签: sql sql-server

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查询?

4 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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