本文介绍了SQL Server:PIVOTing字符串数据的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到一些简单的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

这篇关于SQL Server:PIVOTing字符串数据的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 03:12