1

我有一个由这些列组成的 mysql 表:

user_id,开始,结束,地区

每个用户 id 在每个地区都有一个开始和结束值,如下所示:

+-----------------------------------+
| user_id | start | end  | district |
|       1 |  1000 | 2000 |    north |
|       1 |  1200 | 2200 |    south |
|       2 |   900 | 1900 |    north |
|       2 |   950 | 1700 |    south |
+-----------------------------------+

我正在寻找一个每个 user_id 有一个结果行的选择,它列出了两个区域中每个区域的开始和结束。就像是

select user_id,
(start as no_st, end as no_en where district='north'),
(start as so_st, end as so_en where district='south');

给予:

+-----------------------------------------+
| user_id | no_st | no_en | so_st | so_en |
|       1 |  1000 |  2000 |  1200 |  2200 |
|       2 |   900 |  1900 |   950 |  1700 |
+-----------------------------------------+

有一个神奇的查询吗?

谢谢,巴特...

4

1 回答 1

0

这是透视查询的一种解决方案:

SELECT user_id, 
  MAX(IF(district='north', start, null)) AS no_st,
  MAX(IF(district='north', end, null)) AS no_en,
  MAX(IF(district='south', start, null)) AS so_st,
  MAX(IF(district='south', end, null)) AS so_en
FROM `NoOneEverNamesTheirTableInSQLQuestions`
GROUP BY user_id;
于 2013-07-11T19:09:36.307 回答