简体   繁体   中英

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. I want to access to this table with php and get the result.

Is this even possible?

i want to SELECT id=1,id=2,id=3,id=5 From data group by timestamp;? 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.

 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM