MySQL数据透视查询

时间:2013-05-21 10:45:26

标签: mysql pivot-table

我曾经有过查询

SELECT ps_target_ecpm, ps_actual_ecpm
FROM publisher_stats
JOIN domain ON domain.dmn_id = ps_dmn_id
LEFT JOIN langue ON langue.lng_id = domain.default_lng_id
WHERE MONTH(ps_month) = 05 

我需要的结果应该是

  

may_target_ecmp,may_actual_ecpm,april_target_ecpm,   april_actual_ecpm,march_target_ecpm,march_actual_ecpm。

     

对于4月MONTH(ps_month)= 04和3月MONTH(ps_month)= 03   分别

经过一些询问,我最终得到了一个看起来像这样的查询

SELECT
(CASE WHEN MONTH(ps_month) = 4 THEN ps_target_ecpm ELSE 0 END) AS april_target_ecpm, 
(CASE WHEN MONTH(ps_month) = 4 THEN ps_actual_ecpm ELSE 0 END) AS april_actual_ecpm,
(CASE WHEN MONTH(ps_month) = 3 THEN ps_target_ecpm ELSE 0 END) AS march_target_ecpm, 
(CASE WHEN MONTH(ps_month) = 3 THEN ps_actual_ecpm ELSE 0 END) AS march_actual_ecpm 
FROM publisher_stats
JOIN domain ON domain.dmn_id = ps_dmn_id
LEFT JOIN langue ON langue.lng_id = domain.default_lng_id

我得到的结果集并不是我需要的。 示例响应是:

0           0       0.48    0.27
0.48        0.47    0       0

虽然我需要它在一行

0.48    0.47    0.48    0.27

您能否帮我弄清楚如何使此查询按预期执行。 提前致谢

P.S。这个问题从这个问题开始 - mysql pivoting - how can I fetch data from the same table into different columns?

1 个答案:

答案 0 :(得分:3)

只需使用聚合函数,MAX例如可以正常工作,但如果需要获取每月的总数,则可能需要使用SUM,如果{ps_target_ecpm有多个条目1}}每个月。像这样:

SELECT
  MAX(CASE WHEN MONTH(ps_month) = 4 THEN ps_target_ecpm ELSE 0 END) AS april_target_ecpm, 
  MAX(CASE WHEN MONTH(ps_month) = 4 THEN ps_actual_ecpm ELSE 0 END) AS april_actual_ecpm,
  MAX(CASE WHEN MONTH(ps_month) = 3 THEN ps_target_ecpm ELSE 0 END) AS march_target_ecpm, 
  MAX(CASE WHEN MONTH(ps_month) = 3 THEN ps_actual_ecpm ELSE 0 END) AS march_actual_ecpm 
FROM publisher_stats
JOIN domain ON domain.dmn_id = ps_dmn_id
LEFT JOIN langue ON langue.lng_id = domain.default_lng_id