gpt4 book ai didi

sql - 旋转 SQL 表

转载 作者:行者123 更新时间:2023-12-02 06:20:24 25 4
gpt4 key购买 nike

我有如下表格

Code        Attribute        Value
--------------------------------------
USA Population 300M
USA Language US English
CANADA Population 30M
USA Capital DC
CANADA Language CA English

我怎样才能将表格旋转 90 度并生成如下所示的 View 以运行querysp 在上面?

Code        Language        Population       Capital
------------------------------------------------------
USA US English 300M DC
CANADA CA English 30M NULL

最佳答案

您可以使用 PIVOT(对于 SQL Server 2005+):

SELECT *
FROM YourTable AS T
PIVOT (MIN(Value) FOR Attribute IN ([Language],[Population],[Capital]) AS PT

对于所有版本的 SQL Server 你都可以使用这个:

SELECT  Code, 
MIN(CASE WHEN Attribute = 'Language' THEN Value END) [Language],
MIN(CASE WHEN Attribute = 'Population' THEN Value END) [Population],
MIN(CASE WHEN Attribute = 'Capital' THEN Value END) [Capital]
FROM YourTable
GROUP BY Code

关于sql - 旋转 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11621251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com