简体   繁体   中英

SQL query to get columns based on value

I have a table like below

user_id  | month,     | value
---------+------------+--------
1        | 2013-02-01 | 1
1        | 2013-01-01 | 0
1        | 2013-03-01 | 5
2        | 2013-02-01 | 1

Supposedly a user_id can not have same month more than one.

Let's say I can put the months I want to query in the query statement. like below

SELECT user_id, (bla bla bla) AS '2013-03-01', (bla bla bla) AS '2013-02-01'

How do I get a result like below, with minimum number of queries and post-processing (eg using python or php)?

user_id  | 2013-03-01 | 2013-02-01 | 2013-01-01 
---------+------------+------------+------------
1        | 5          | 1          | 0
2        | NULL       | 1          | NULL

You can use conditional aggregates to get the required result set:

SELECT user_id,
       MAX(CASE WHEN month = '2013-03-01' THEN value END) AS '2013-03-01',
       MAX(CASE WHEN month = '2013-02-01' THEN value END) AS '2013-02-01',
       MAX(CASE WHEN month = '2013-01-01' THEN value END) AS '2013-01-01'
FROM mytable
GROUP BY user_id

This works as long there is a predefined set of month values. Otherwise you have to use dynamic SQL.

Fiddle Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM