SQL Server:PIVOTingstring数据的示例
试图find一些简单的SQL Server PIVOT示例。 我发现的大部分例子都涉及计算或总结数字。 我只是想旋转一些string数据。 例如,我有一个查询返回以下内容。
Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT
我想用PIVOT(如果可能的话)做出如下结果:
Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT
这甚至可能与PIVOTfunction?
请记住,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
如果您特别想使用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
表格设置:
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
两个查询结果:
那么,对于你的样品和任何有限数量的独特列,这应该做到这一点。
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
从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
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;