简体   繁体   English

SQL查询以基于值获取列

[英]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. 假设一个user_id month不能超过一个。

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)? 如何获得最少查询和后处理次数(例如,使用python或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. 只要存在一组预定义month值,此方法就起作用。 Otherwise you have to use dynamic SQL. 否则,您必须使用动态SQL。

Fiddle Demo here 小提琴演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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