如何扩展在SQL语句中创建额外的列而不是使用GROUP BY创建额外的行?

时间:2017-12-09 20:36:00

标签: sql mariadb pivot-table

此处提到了数据库的架构:http://sqlzoo.net/wiki/Guest_House

该请求是针对2016-11-14开始的一周中的每一天显示当天有多少客人按楼层号查看。

决赛桌应该是这样的(当然,列的命名并不重要):

+------------+-----+-----+-----+
| i          | 1st | 2nd | 3rd |
+------------+-----+-----+-----+
| 2016-11-14 |   5 |   3 |   4 |
| 2016-11-15 |   6 |   4 |   1 |
| 2016-11-16 |   2 |   2 |   4 |
| 2016-11-17 |   5 |   3 |   6 |
| 2016-11-18 |   2 |   3 |   2 |
| 2016-11-19 |   5 |   5 |   1 |
| 2016-11-20 |   2 |   2 |   2 |
+------------+-----+-----+-----+

尝试使用SQL为中间列(2nd)实现它时导致了这个脚本:

select ADDDATE(booking_date, nights) as checkout, count(distinct guest_id) as '2nd'
from booking
where CAST(room_no as char) like '2%'
and ADDDATE(booking_date, nights) >= '2016-11-14'
group by checkout
order by checkout
LIMIT 7

问题是此脚本一次只生成一列

这是一个可扩展的版本,但这只是每行:

select ADDDATE(booking_date, nights) as checkout,
SUBSTR(CAST(room_no as char), 1, 1) as floor, count(distinct guest_id) as 'guest count'
from booking
where ADDDATE(booking_date, nights) >= '2016-11-14'
group by checkout, floor
order by checkout, floor
LIMIT 21

并且这种方法的格式化输出并不理想:

checkout  floor guest count
2016-11-14  1   5
2016-11-14  2   3
2016-11-14  3   4
2016-11-15  1   6
2016-11-15  2   4
2016-11-15  3   1
2016-11-16  1   2
2016-11-16  2   2
2016-11-16  3   4
2016-11-17  1   5
2016-11-17  2   3
2016-11-17  3   6
2016-11-18  1   2
2016-11-18  2   3
2016-11-18  3   2
2016-11-19  1   5
2016-11-19  2   5
2016-11-19  3   1
2016-11-20  1   2
2016-11-20  2   2
2016-11-20  3   2

1 个答案:

答案 0 :(得分:0)

两倍的列与两倍的行==在缩放上没有太大差异。并且列数的小的限制。

转到更多行,然后使用数据透视显示为列。 (参见[pivot-table]标签)