透视到多列

时间:2017-04-18 09:16:24

标签: sql sql-server select request pivot

我有一个查询1列AFFECTED_ITEM到3个表。

如何对2列AFFECTED_ITEM和ASSIGN执行相同的查询?

这是对1列AFFECTED_ITEM到3个表

的查询
SELECT
 AFFECTED_ITEM,
   Table1,
   Table2,
   Table3

FROM (
SELECT  'Table1' as Tab, AFFECTED_ITEM, Count(*) as AFFECTED_ITEMS from [dbo].[CM3RM1] WHERE ORIG_DATE_ENTERED between (@StartDate) and @EndDate + 1
and [AFFECTED_ITEM] in (@Affected_Item) and [COMPANY] in (@Company) and [ASSIGNED_TO] in (@Assignee) group by AFFECTED_ITEM
UNION ALL
SELECT  'Table2' as Tab, AFFECTED_ITEM, Count(*) as AFFECTED_ITEMS from [dbo].[INCIDENTSM1]  WHERE  OPEN_TIME between (@StartDate) and @EndDate + 1
and [AFFECTED_ITEM] in (@Affected_Item) and [COMPANY] in (@Company) and [ASSIGNEE] in (@Assignee) group by AFFECTED_ITEM
UNION ALL
SELECT  'Table3' as Tab, AFFECTED_ITEM, Count(*) as AFFECTED_ITEMS from [dbo].[PROBSUMMARYM1] WHERE  OPEN_TIME between @StartDate and @EndDate + 1
and [AFFECTED_ITEM] in (@Affected_Item) and [COMPANY] in (@Company)and  [ASSIGNEE_NAME] in (@Assignee) and [DDC_RESP_COMPANY] in (@Resp_Company) group by AFFECTED_ITEM
 ) t
PIVOT (SUM(AFFECTED_ITEMS) FOR Tab IN (Table1,Table2,Table3)
)as p

0 个答案:

没有答案