带有文本标识符和数字值的数据透视表

时间:2018-06-08 14:08:49

标签: sql sql-server pivot

如何使用文本标识符和数字值来转动表格?

这是我的表(服务):

Street   | Service       | Total
---------|---------------|------
Street A | Service AA 01 | 20
Street A | Service AB 01 | 10
Street A | Service AB 01 | 15
Street A | Service AC 01 | 05
Street B | Service AA 01 | 10
Street B | Service AA 01 | 03
Street B | Service AB 01 | 05
Street B | Service AC 01 | 03

这是我想要的结果:

Street   | Service AA 01 | Service AB 01 | Service AC 01
---------|---------------|---------------|--------------
Street A |            20 |            25 |            05
Street B |            13 |            05 |            03

到目前为止我尝试了什么:

SELECT Street, ['SERVICE AA 01'], ['SERVICE AB 01'], ['SERVICE AC 01']
FROM services PIVOT (
  SUM(Total) FOR Service IN (['SERVICE AA 01'], ['SERVICE AB 01'], ['SERVICE AC 01'])) AS D

获得街道,所有列,但所有值始终为 null ;

2 个答案:

答案 0 :(得分:2)

在我见过的每个PIVOT示例中,您必须从Derived表中选择,而不是直接从表中选择。

哦,同样根据this answer,你不要在你的列名中加上单引号。

显然你必须做这样的事情:

SELECT Street, [SERVICE AA 01], [SERVICE AB 01], [SERVICE AC 01]
FROM (SELECT Street, Service, Total FROM services) AS S
PIVOT (
  SUM(Total) FOR Service IN ([SERVICE AA 01], [SERVICE AB 01], [SERVICE AC 01])) AS D

答案 1 :(得分:1)

您的问题是[SERVICE AA 01]['SERVICE AA 01']没有引用相同的列名。第二个在列名中有单引号 - 这是一个非常糟糕的做法而不是问题。

我会做一个编辑评论,如果你用下划线而不是空格(SERVICE_AA_01)命名列,那么你就不需要转义它们了。而且你可能也不会引用它们。你不会遇到这个问题。只是说。良好的命名约定可以防止出现问题和混淆。

我也会使用条件聚合:

select street,
       sum(case when Service = 'SERVICE AA 01' then total end) as [SERVICE AA 01],  
       sum(case when Service = 'SERVICE AB 01' then total end) as [SERVICE AB 01], 
       sum(case when Service = 'SERVICE AC 01' then total end) as [SERVICE AC 01] from services
group by street;

我发现pivot语法不是特别强大或简洁。正如Tab所指出的那样,通常使用子查询,因为无关的列在pivot中做了各种各样的事情。这不是问题,但经常发生。

相关问题