1

I used to have a query

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 

The result I need should look like

may_target_ecmp, may_actual_ecpm, april_target_ecpm, april_actual_ecpm, march_target_ecpm, march_actual_ecpm.

For april MONTH(ps_month) = 04 and for march MONTH(ps_month) = 03 respectively.

After some questioning around I ended up with a query that looks like this

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

The resultset I get is not quite what I need. The example response is:

0           0       0.48    0.27
0.48        0.47    0       0

While I need it to be in one row

0.48    0.47    0.48    0.27

Could you please help me to figure out how to make this query do what it is intended to. Thanks in advance

P.S. This question come all the way from this question - mysql pivoting - how can I fetch data from the same table into different columns?

4

1 回答 1

3

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

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
于 2013-05-21T10:48:42.963 回答