2016-08-09 5 views
0

選択したIDにすべてのX値が必要であり、等しい場合はタイムスタンプを結合します。 私はこのテーブルにphpでアクセスして結果を得たいです。UNIONに同じテーブルを照会して新しい列を作成する方法mysql?

これも可能ですか?

私はしたい SELECT id = 1、id = 2、id = 3、id = 5タイムスタンプ別データグループから;多くのidsがありますが、私はidsを選択し、異なる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 |  
+----------------+------+------+------+------+ 

答えて

1

はあなたの結果をpivotするconditional aggregationを使用することができ、あなたが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 

私は61.01.16 20:59:22値を仮定しなければなりません3番目のxではなく、4番目の。