Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

pivot - mysql pivoting - how can I fetch data from the same table into different columns?

I have a query that looks like this

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 set I need should include fields like this:

    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.

I tried union, subqueries and so on - still no success. My experiments lead me to this so far, but obviously it is not what needed

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

What would be the right query to accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can try this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...