gpt4 book ai didi

mysql - 如何在同一个表上查询 UNION 并创建新列 mysql?

转载 作者:行者123 更新时间:2023-11-29 11:21:19 26 4
gpt4 key购买 nike

我需要所选 id 的所有 X 值,如果相等则合并时间戳。我想用 php 访问这个表并得到结果。

这可能吗?

我想要 按时间戳从数据组中选择 id=1,id=2,id=3,id=5;?有很多 id,但我需要一个查询,我可以在其中选择 id 并获得将来自不同 id 的多个 x 值的相等时间戳组合在一起的结果。

 Table'data'         
+--+-------+--------+---+--+---------+------+
|id| timestamp | Name | X | Y | other|
+--+-------+--------+---+--+---------+------+
| 1|1.01.14 19:59:21| Müller | 3 | 1 | 1|
| 2|1.01.14 19:59:21| Schmidt| 5 | 2 | 2|
| 3|1.01.16 20:59:22| Taler | 6 | 3 | 1|
| 5|1.01.14 19:59:21| Paul | 10| 2 | 3|
+--+-------+--------+---+--+---------+------+

需要输出:

 Table'data'         
+----------------+------+------+------+------+-- -+ ---+----+----+
| timestamp | id | id | id | id | X | X | X | X |
+----------------+------+------+------+------+-- -+ ---+--- +----+
|1.01.14 19:59:21| 1 | 2 | null | 5 | 3 | 5 |null| 10 |
|1.01.16 20:59:22| null| null| 3 | null|null|null| 6 |null|
+----------------+------+------+------+------+----+----+----+----+

OR:

Table'data' Output:
+----------------+------+------+------+------+
| timestamp | id | id | id | id |
+----------------+------+------+------+------+
|1.01.14 19:59:21| 3 | 5 |null | 10 |
|1.01.16 20:59:22|null |null | 6 | null |
+----------------+------+------+------+------+

最佳答案

假设您知道 id 值,您可以使用条件聚合透视您的结果:

select timestamp,
max(case when id = 1 then id end) id1,
max(case when id = 2 then id end) id2,
max(case when id = 3 then id end) id3,
max(case when id = 5 then id end) id5,
max(case when id = 1 then x end) x1,
max(case when id = 2 then x end) x2,
max(case when id = 3 then x end) x3,
max(case when id = 5 then x end) x5
from yourtable
group by timestamp

我假设对于 1.01.16 20:59:226 的值应该位于第 3 个 x,而不是第 4 个。

关于mysql - 如何在同一个表上查询 UNION 并创建新列 mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860955/

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