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 

我的大脑已经冻结所以需要帮助?

如何构造这个非透视查询?

4

4 回答 4

1

我建议不要将多个值放在ReasonSql 查询中的单个列 ( ) 中,如果您希望以这种方式查看数据,则将其留给您的表示层...

但这是在 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
于 2013-02-15T15:32:33.043 回答
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
于 2013-02-15T15:35:15.397 回答
1

您可以使用UNPIVOT,CROSS 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

或者您可以使用UNPIVOT,STUFFFOR 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

于 2013-02-15T15:35:27.097 回答
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 小提琴

于 2013-02-15T15:35:51.237 回答