SQL Server:透视字符串数据的示例

2021-12-02 00:00:00 pivot tsql sql-server

试图找到一些简单的 SQL Server PIVOT 示例.我发现的大多数例子都涉及对数字进行计数或求和.我只想旋转一些字符串数据.例如,我有一个返回以下内容的查询.

Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.

Action1 VIEW  
Action1 EDIT  
Action2 VIEW  
Action3 VIEW  
Action3 EDIT  

我想使用 PIVOT(如果可能的话)来产生这样的结果:

I would like to use PIVOT (if even possible) to make the results like so:

Action1 VIEW EDIT  
Action2 VIEW NULL  
Action3 VIEW EDIT  

这是否可以通过 PIVOT 功能实现?

Is this even possible with the PIVOT functionality?

推荐答案

请记住,MAX 聚合函数将适用于文本和数字.这个查询只需要扫描一次表.

Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.

SELECT Action,
       MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, 
       MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
 FROM t
 GROUP BY Action

相关文章