mysql pivoting - 如何将同一个表中的数据提取到不同的列中?

时间:2013-05-10 08:54:48

标签: mysql pivot

我有一个看起来像这样的查询

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.

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

我尝试过工会,子查询等等 - 仍然没有成功。 到目前为止,我的实验让我想到了这一点,但显然它并不是什么需要

SELECT a.ps_dmn_id, a.ps_actual_ecpm AS mayecmp, b.ps_actual_ecpm AS aprilecpm
FROM
(
    SELECT *
    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 
) AS a,
(
    SELECT *
    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) = 04
) AS b

GROUP by ps_dmn_id

完成此任务的正确查询是什么?

1 个答案:

答案 0 :(得分:1)

你可以试试这个

SELECT ( CASE WHEN ps_month = '04' THEN ps_target_ecpm
              ELSE 0
         END ) AS april_target_ecmp
       ,( CASE WHEN ps_month = '04' THEN ps_actual_ecpm
               ELSE 0
          END ) AS april_actual_ecpm
       ,( CASE WHEN ps_month = '03' THEN ps_target_ecpm
               ELSE 0
          END ) AS march_target_ecmp
       ,( CASE WHEN ps_month = '03' 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