gpt4 book ai didi

MySQL SELECT 行作为连续列

转载 作者:行者123 更新时间:2023-11-29 12:22:13 25 4
gpt4 key购买 nike

我在 MySQL 数据库中有一个名为“Values”的表:

sp_id   W   Value_C Top_C
742 11 11.42 1.15
742 12 114.35 2.44
742 13 27.2 0.42
742 14 55.38 6.2
742 15 23.77 16.7
15 11 10.59 9.15
15 12 12.4 12.3
15 13 157.89 0.72
15 14 51.2 1.5
15 15 11.78 0.51
117 11 27.48 0.92
117 12 21.416 0.76
117 13 75.31 0.39
117 14 2.182 0.79
252 11 15.54 0.25
252 12 10.209 0.32
252 13 14.41 0.44
252 14 68.34 2.16

我正在寻找重新排列数据。我希望得到这个:

sp_id  11       11      12      12      13      13      14      14      15      15
742 11.42 1.15 114.35 2.44 27.2 0.42 55.38 6.2 23.77 6.77
15 10.59 9.15 12.4 12.3 157.89 0.72 51.2 1.5 11.78 0.51
117 27.48 0.92 21.416 0.76 75.31 0.39 2.182 0.79 NULL NULL
252 15.54 0.25 10.209 0.32 14.41 0.44 68.34 2.16 NULL NULL

我可以将它们作为列,但我很难将它们作为行。当我使用 CASE 时,我在很多地方都得到 NULL

如何使用 MySQL 查询SELECT这个子集?

编辑:更正了标题。

最佳答案

如果 W 值有限,您可以尝试这样的操作:

SQL Fiddle

MySQL 5.5.32 架构设置:

CREATE TABLE ValuesTable
(`sp_id` int, `W` int, `Value_C` decimal(10,2), `Top_C` decimal(10,2))
;

INSERT INTO ValuesTable
(`sp_id`, `W`, `Value_C`, `Top_C`)
VALUES
(742, 11, 11.42, 1.15),
(742, 12, 114.35, 2.44),
(742, 13, 27.2, 0.42),
(742, 14, 55.38, 6.2),
(742, 15, 23.77, 16.7),
(15, 11, 10.59, 9.15),
(15, 12, 12.4, 12.3),
(15, 13, 157.89, 0.72),
(15, 14, 51.2, 1.5),
(15, 15, 11.78, 0.51),
(117, 11, 27.48, 0.92),
(117, 12, 21.416, 0.76),
(117, 13, 75.31, 0.39),
(117, 14, 2.182, 0.79),
(252, 11, 15.54, 0.25),
(252, 12, 10.209, 0.32),
(252, 13, 14.41, 0.44),
(252, 14, 68.34, 2.16)
;

查询 1:

SELECT DISTINCT VT.sp_id, 
VT11.Value_C as 11v, VT11.Top_C as 11t,
VT12.Value_C as 12v, VT12.Top_C as 12t,
VT13.Value_C as 13v, VT13.Top_C as 13t,
VT14.Value_C as 14v, VT14.Top_C as 14t,
VT15.Value_C as 15v, VT15.Top_C as 15t
FROM ValuesTable VT
LEFT OUTER JOIN ValuesTable VT11 ON VT.sp_id = VT11.sp_id AND VT11.W = 11
LEFT OUTER JOIN ValuesTable VT12 ON VT.sp_id = VT12.sp_id AND VT12.W = 12
LEFT OUTER JOIN ValuesTable VT13 ON VT.sp_id = VT13.sp_id AND VT13.W = 13
LEFT OUTER JOIN ValuesTable VT14 ON VT.sp_id = VT14.sp_id AND VT14.W = 14
LEFT OUTER JOIN ValuesTable VT15 ON VT.sp_id = VT15.sp_id AND VT15.W = 15

<强> Results :

| SP_ID |   11V |  11T |    12V |  12T |    13V |  13T |   14V |  14T |    15V |    15T |
|-------|-------|------|--------|------|--------|------|-------|------|--------|--------|
| 742 | 11.42 | 1.15 | 114.35 | 2.44 | 27.2 | 0.42 | 55.38 | 6.2 | 23.77 | 16.7 |
| 15 | 10.59 | 9.15 | 12.4 | 12.3 | 157.89 | 0.72 | 51.2 | 1.5 | 11.78 | 0.51 |
| 117 | 27.48 | 0.92 | 21.42 | 0.76 | 75.31 | 0.39 | 2.18 | 0.79 | (null) | (null) |
| 252 | 15.54 | 0.25 | 10.21 | 0.32 | 14.41 | 0.44 | 68.34 | 2.16 | (null) | (null) |

关于MySQL SELECT 行作为连续列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840077/

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