我正在使用MySQL,并尝试对包含多行数据的表进行排序/连接,以便每年的数据都在相邻列中表示,如果数据不存在,它被表示为 null。
+------+------+------------+
|代码|年 |查询 |
+------+------+------------+
| 1 | 2012 | 302 | 302
| 2 | 2012 | 274 | 274
| 3 | 2012 | 288 | 288
| 4 | 2012 | 301 | 301
| 5 | 2012 | 192 | 192
| 1 | 2013 | 406 | 406
| 3 | 2013 | 297 | 297
| 4 | 2013 | 199 | 199
| 1 | 2014年| 254 | 254
| 2 | 2014年| 396 | 396
| 3 | 2014年| 187 | 187
| 4 | 2014年| 213 | 213
| 5 | 2014年| 316 | 316
| 6 | 2014年| 222 | 222
+------+------+------------+
这样上表将如下所示:
+------+------+------------+------+------------+---- --+------------+
|代码|年 |查询 |年 |查询 |年 |查询 |
+------+------+------------+------+------------+---- --+------------+
| 1 | 2012 | 302 | 302 2013 | 406 | 406 2014年| 254 | 254
| 2 | 2012 | 274 | 274空|空 |空 |空 |
| 3 | 2012 | 288 | 288 2013 | 297 | 297 2014年| 187 | 187
| 4 | 2012 | 301 | 301 2013 | 199 | 199 2014年| 213 | 213
| 5 | 2012 | 192 | 192空 |空 | 2014年| 316 | 316
| 6 |空 |空 |空|空| 2014年| 222 | 222
+------+------+------------+------+------------+---- --+------------+
我认为我应该寻找的是完全外连接,但使用 MySQL 是不可能的。
我设法使用多个 LEFT OUTER JOINS 将多行连接在一起,但这会忽略 3 年来不存在数据的任何行。
最佳答案
由于您显示的记录数量有限, 您可以编写一个简单的枢轴解决方案,如下所示。
但是,如果年数增加,则必须在运行时生成此查询并执行。
mysql> select
-> code
-> , max( case when year=2012 then year end ) as y2012
-> , max( case when year=2012 then enquiries end ) as enq_2012
-> , max( case when year=2013 then year end ) as y2013
-> , max( case when year=2013 then enquiries end ) as enq_2013
-> , max( case when year=2014 then year end ) as y2014
-> , max( case when year=2014 then enquiries end ) as enq_2014
-> from so_20150521.so_q30374911
-> group by code
-> order by code;
+------+-------+----------+-------+----------+-------+----------+
| code | y2012 | enq_2012 | y2013 | enq_2013 | y2014 | enq_2014 |
+------+-------+----------+-------+----------+-------+----------+
| 1 | 2012 | 302 | 2013 | 406 | 2014 | 254 |
| 2 | 2012 | 274 | NULL | NULL | 2014 | 396 |
| 3 | 2012 | 288 | 2013 | 297 | 2014 | 187 |
| 4 | 2012 | 301 | 2013 | 199 | 2014 | 213 |
| 5 | 2012 | 192 | NULL | NULL | 2014 | 316 |
| 6 | NULL | NULL | NULL | NULL | 2014 | 222 |
+------+-------+----------+-------+----------+-------+----------+
6 rows in set (0.02 sec)
SQL Fiddle 演示,位于 http://sqlfiddle.com/#!9/4a46d/2
进一步简化可以是:
mysql> select
-> code
-> , max( case when year=2012 then enquiries end ) as enq_2012
-> , max( case when year=2013 then enquiries end ) as enq_2013
-> , max( case when year=2014 then enquiries end ) as enq_2014
-> from so_20150521.so_q30374911
-> group by code
-> order by code;
+------+----------+----------+----------+
| code | enq_2012 | enq_2013 | enq_2014 |
+------+----------+----------+----------+
| 1 | 302 | 406 | 254 |
| 2 | 274 | NULL | 396 |
| 3 | 288 | 297 | 187 |
| 4 | 301 | 199 | 213 |
| 5 | 192 | NULL | 316 |
| 6 | NULL | NULL | 222 |
+------+----------+----------+----------+
6 rows in set (0.00 sec)
关于MYSQL:将行连接为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374911/