如何在同一个表mysql中将datetime的查询结果合并?

时间:2012-04-02 09:11:02

标签: mysql datetime merge

所有

我需要你的帮助才能在mysql的同一日期时间内合并结果。

查询两个表,如:

SELECT b.ID, b.DateTime, b.Value 
FROM tableA a, tableB b 
WHERE (a.Id=1) OR (a.Id=2) OR (a.Id=3) AND (a.Id = b.ID) 
      AND (b.DateTime Between '2011-04-02 06:00' And '2011-04-02 06:05')

查询结果:

| ID  |    DateTime      | Value |
----------------------------------
| 1   | 2011-04-02 06:00 | 20    | 
| 1   | 2011-04-02 06:05 | 21    | 
| 2   | 2011-04-02 06:00 | 10    | 
| 2   | 2011-04-02 06:05 | 16    | 
| 3   | 2011-04-02 06:00 | 23    | 
| 3   | 2011-04-02 06:05 | 22    |

我想要的只是让结果

|    DateTime      | ID_1    | ID_2   | ID_3   | 
------------------------------------------------
| 2011-04-02 06:00 |  20     |   10   | 23     | 
| 2011-04-02 06:05 |  21     |   16   | 22     | 

我希望有一个解决方案。

感谢您的帮助。

问候,
YougyZ

1 个答案:

答案 0 :(得分:0)

感谢@liquorvicar提供解决方案......

我试过这个问题:

SELECT b.Date, 
SUM(CASE WHEN a.Id=1 THEN b.Value ELSE 0 END) AS Mac1, 
SUM(CASE WHEN a.Id=2 THEN b.Value ELSE 0 END) AS Mac2, 
SUM(CASE WHEN a.Id=3 THEN b.Value ELSE 0 END) AS Mac3 
FROM TableA a, TableB b 
WHERE (a.Id = b.ID) AND (b.Date Between '2011-04-02 06:00' And '2011-04-02 06:05') 
GROUP BY b.DA_Date 

结果就像我需要的那样...... :)