当前位置:  开发笔记 > 编程语言 > 正文

SQL Server:PIVOTing字符串数据的示例

如何解决《SQLServer:PIVOTing字符串数据的示例》经验,为你挑选了6个好方法。

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

Action1 VIEW  
Action1 EDIT  
Action2 VIEW  
Action3 VIEW  
Action3 EDIT  

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

Action1 VIEW EDIT  
Action2 VIEW NULL  
Action3 VIEW EDIT  

PIVOT功能可以实现这一点吗?



1> John Hubert..:

请记住,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


哪个更快,这还是PIVOT?

2> mxasim..:

表格设置:

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

两个查询结果:
在此输入图像描述



3> Miles D..:

如果您特别想使用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



4> 小智..:

来自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



5> vzczc..:

那么,对于您的样本和任何具有有限数量的唯一列,这应该这样做.

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



6> mr_eclair..:
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;

推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有