[英]How to query UNION over same table and create new columns mysql?
I need all X values for selected ids and unite the timestamp if it is equal. 我需要所有X值用于选定的ID,并且如果相等则统一时间戳。 I want to access to this table with php and get the result. 我想使用php访问此表并获取结果。
Is this even possible? 这有可能吗?
i want to SELECT id=1,id=2,id=3,id=5 From data group by timestamp;? 我想从时间戳按数据组选择id = 1,id = 2,id = 3,id = 5; there are many ids but i need a query where i can choose the ids and get a result where equal timestamp of multiple x values from different ids is combined. 有很多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|
+--+-------+--------+---+--+---------+------+
Need Output: 需要输出:
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 |
+----------------+------+------+------+------+
Assuming you know the id
values, you can use conditional aggregation
to pivot
your results: 假设你知道的id
值,可以使用conditional aggregation
到pivot
结果:
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
I assume for 1.01.16 20:59:22
the value of 6
should be in the 3rd x
, not the 4th. 我假设对于1.01.16 20:59:22
6
的值应该在第3个x
,而不是第4个中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.