数据透视和类别

时间:2020-02-26 14:01:23

标签: sql tsql pivot

我的字段有许多不同的名称,例如:

Partner
Partner UK
Partner USA
Associate - Senior
Associate - Junior
Junior Associate

以此类推(数据中的数据比我此处包含的更多)。

我本来是按照以下方式对数据进行透视的:

...pivot (count([NAME] for employee_rank in ([Partner], [Associate], [Analyst]) as pivottable

直到我意识到我错过了每个级别的所有子变量。

是否可以使枢轴类别更加灵活,例如:

...pivot (count([NAME] for employee_rank in ([LIKE '%Partner%'], [LIKE '%Associate%'], [LIKE '%Analyst%']) as pivottable

1 个答案:

答案 0 :(得分:0)

不,您不能使用PIVOT来做到这一点。我建议您看看Cross Tab,它更灵活。

这是伪SQL,但是看起来像这样:

SELECT {GROUP BY Columns},
       COUNT(CASE WHEN employee_rank LIKE '%Partner%' THEN [Name] END) AS Partners,
       COUNT(CASE WHEN employee_rank LIKE '%Associate%' THEN [Name] END) AS Associates,
       ...
FROM YourTable
WHERE ...
GROUP BY {GROUP BY Columns};