gpt4 book ai didi

SQL Server : how to transpose rows into columns

转载 作者:行者123 更新时间:2023-12-01 14:01:19 25 4
gpt4 key购买 nike

在 T-SQL 中,我试图将某些行的值转置为列。
初始表:

Project | Machine | Value
-------------------------
A X 100
A Y 99
A Z 98
A W 97
B X 97
B Y 96
B W 95
C X 95
C Z 94

我想要的结果:
Project     MX  MY  MZ  MW
-----------------------------
A 100 99 98 97
B 97 96 0 95
C 95 0 94 0

我已经创建了测试代码:
CREATE TABLE Company (project char(1), machine char(1), cost int)
GO

INSERT INTO Company
VALUES ('A', 'X', 100), ('A', 'Y', 99), ('A', 'Z', 98),
('A', 'W', 97), ('B', 'X', 97), ('B', 'Y', 96),
('B', 'W', 95), ('C', 'X', 95), ('C', 'Z', 94);

我的数据透视查询:
SELECT
project, 'X', 'Y', 'Z', 'W'
FROM
(SELECT
project, machine, cost
FROM
Company) p
PIVOT
(MAX(cost)
FOR machine IN ('X', 'Y', 'Z', 'W') AS pvt

我收到此错误:

Incorrect syntax near ''X''



我的数据透视查询错了吗?

提前致谢

最佳答案

如果你的机器有限,那么我会做条件聚合而不是 PIVOT :

SELECT Project,
MAX(CASE WHEN machine = 'X' THEN cost END) AS MX,
MAX(CASE WHEN machine = 'Y' THEN cost END) AS MY,
MAX(CASE WHEN machine = 'Z' THEN cost END) AS MZ,
MAX(CASE WHEN machine = 'W' THEN cost END) AS MW
FROM Company c
GROUP BY Project;

如果你想和 PIVOT一起去,然后我将修复缺少右括号的语法错误:
SELECT * 
FROM (SELECT project, machine, cost
FROM Company
) AS p PIVOT
(MAX(cost)
FOR machine IN ([X], [Y], [Z], [W])
) AS pvt;

笔记 :
  • 不要使用单引号作为列名,而是使用方括号。
  • 关于SQL Server : how to transpose rows into columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52782231/

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