MySql数据透视表或加入麻烦

时间:2014-03-05 21:23:27

标签: mysql join pivot

我有一张表,如下所示:

pkey|ICAO|   Dt     |Tm      |Temp|Dew
0   |KPHL|2014-03-05|00:00:00|46  |32
1   |KPHL|2014-03-05|01:00:00|45  |33
2   |KPHL|2014-03-05|02:00:00|44  |32
3   |KABI|2014-03-05|00:00:00|46  |32
4   |KABI|2014-03-05|01:00:00|46  |32
5   |KABI|2014-03-05|01:00:00|46  |32
6   |KPHL|2014-03-06|00:00:00|47  |32
7   |KPHL|2014-03-06|01:00:00|48  |33
8   |KPHL|2014-03-06|02:00:00|45  |32
9   |KABI|2014-03-06|00:00:00|42  |32
10  |KABI|2014-03-06|01:00:00|44  |32
11  |KABI|2014-03-06|01:00:00|60  |32

..等等......

我希望我的查询显示KPHL的所有临时值,日期范围,比如今天,3/5和明天3/6,并且并排显示它们......比如

Tm      | Today | Tomorrow
00:00:00| 46    | 47
01:00:00| 45    | 48
02:00:00| 44    | 45

我不确定是否需要某种连接或数据透视表。我看了很多,但找不到模仿我想做的事情,而且我尝试过的东西都没用。

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合执行此操作:

select tm,
       max(case when dt = dt(now()) then temp end) as today,
       max(case when dt = dt(now() + interval 1 day) then temp end) as tomorrow
from table t
where icao = 'KPHL' and
      dt between date(now()) and dt(now() + interval 1 day)
group by tm
order by tm;

答案 1 :(得分:0)

假设每次有一个临时等,

SELECT tm
      ,MAX(CASE dt WHEN '2014-03-05' THEN Temp ELSE NULL END) AS Today
      ,MAX(CASE dt WHEN '2014-03-06' THEN Temp ELSE NULL END) AS Tomorrow
  FROM x
  WHERE dt IN ('2014-03-05', '2014-03-06')
    AND ICAO = 'KPHL'
  GROUP BY tm
  ORDER BY tm