试图找到一些简单的SQL Server PIVOT示例.我发现的大多数例子都涉及计算或总结数字.我只想转动一些字符串数据.例如,我有一个返回以下内容的查询.
Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT
我想使用PIVOT(如果可能的话)来产生如下结果:
Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT
PIVOT功能可以实现这一点吗?
请记住,MAX聚合函数将对文本和数字起作用.此查询仅需要扫描一次表.
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
表格设置:
CREATE TABLE dbo.tbl ( action VARCHAR(20) NOT NULL, view_edit VARCHAR(20) NOT NULL ); INSERT INTO dbo.tbl (action, view_edit) VALUES ('Action1', 'VIEW'), ('Action1', 'EDIT'), ('Action2', 'VIEW'), ('Action3', 'VIEW'), ('Action3', 'EDIT');
你的桌子:
SELECT action, view_edit FROM dbo.tbl
不使用PIVOT查询:
SELECT Action, [View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'), [Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT') FROM tbl t GROUP BY Action
使用PIVOT查询:
SELECT [Action], [View], [Edit] FROM (SELECT [Action], view_edit FROM tbl) AS t1 PIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2
两个查询结果:
如果您特别想使用SQL Server PIVOT函数,那么这应该可行,假设您的两个原始列称为act和cmd.(虽然看起来不太漂亮.)
SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit' FROM ( SELECT act, cmd FROM data ) AS src PIVOT ( MAX(cmd) FOR cmd IN ([View], [Edit]) ) AS pvt
来自http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:
SELECT CUST, PRODUCT, QTY FROM Product) up PIVOT ( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p UNPIVOT (QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS) ) AS Unpvt GO
那么,对于您的样本和任何具有有限数量的唯一列,这应该这样做.
select distinct a, (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'), (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT') from t t1
With pivot_data as ( select action, -- grouping column view_edit -- spreading column from tbl ) select action, [view], [edit] from pivot_data pivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p;