SQLServer:旋转字符串数据的示例试图找到一些简单的SQLServer枢轴示例。我发现的大多数例子都涉及计数或汇总数字。我只想转轴一些字符串数据。例如,我有一个返回以下内容的查询。Action1 VIEW Action1 EDIT
Action2 VIEW Action3 VIEW Action3 EDIT我想使用枢轴(如果可能的话)来得出这样的结果:Action1 VIEW EDIT
Action2 VIEW NULL Action3 VIEW EDIT这与枢轴功能是可能的吗?
3 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
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
12345678_0001
TA贡献1802条经验 获得超5个赞
SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'FROM ( SELECT act, cmd FROM data) AS srcPIVOT ( MAX(cmd) FOR cmd IN ([View], [Edit])) AS pvt
慕姐8265434
TA贡献1813条经验 获得超2个赞
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
查询时不使用枢轴:
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 tGROUP BY Action
使用枢轴查询:
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
这两个查询结果都是:
添加回答
举报
0/150
提交
取消