SQL Server透视具有多行的多个值

时间:2018-05-21 16:55:36

标签: sql-server pivot

SQL Server中的Pivots对我来说是新手,并且一直在努力想出下面图像中的结果。部门是随机的。我正在查看一个未知的列名称数据透视查询,但我无法弄明白。该表将有数千行,最多50个部门。任何帮助将不胜感激。

这就是我的尝试:

select department, employees, pct, up_down
from
(
  select employees, department
  from etl_insight_counts
) d
pivot
(
  max(employees)
  for department in (department, employees, pct, up_down)
) piv;

这是我想要实现的示例数据和结果。 enter image description here

2 个答案:

答案 0 :(得分:0)

我正在使用此引用Efficiently convert rows to columns in sql server和其他一些引用,我提出了这个查询

DECLARE @cols NVARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT a.department 
                       FROM_insight_counts a FOR XML PATH(''), TYPE).VALUE('.', 'NVARCHAR(MAX)')

SET @query = N'select *
from
(
  select id_request, department, employees, ca.pct, ca.up_down
  from etl_insight_counts
  CROSS APPLY (VALUES (pct, up_down)) ca (pct, up_down)
) d
pivot
(
  max(employees)
  for department in ('+@cols+')
) piv'

exec sp_executesql @query;

希望它按预期工作

答案 1 :(得分:0)

这是我最终提出的,将事情拼凑在一起。它将动态地计算X个要转动的列数(@cols),然后将它们包含在数据结果...

DECLARE @cols NVARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.dpt) 
                      from etl_insight_counts
                      cross apply 
                      (
                        select department as dpt 
                        union all
                        select department as dpt2
                      ) c 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = N'select *
from
(
  select id_request, department, employees, max(ca.up_down) as ud
  from etl_insight_counts 
  Group By id_request, department, employees
) d
pivot
(
  max(employees)
  for department in ('+@cols+')
) piv'

exec sp_executesql @query;

对于每个值(例如:max(ca.up_down)),您需要一个单独的数据透视查询。我将每个数据透视查询放入一个视图中。为简单起见,我使用MS-Access按结果中的任何已知列过滤结果,并可选择将视图列连接到其他数据源以支持快速数据分析。希望这可以帮助将来的某个人。