MySQL将groupBy子句拆分为多个列

时间:2018-09-13 06:54:45

标签: php mysql database

我对复杂的MySQL查询的知识不好,并且我在搜索甚至措辞上都遇到问题。

我有一张看起来如下的表格。 enter image description here

我有一个查询,对“类型=学生”的所有行进行计数,然后按年份和月份对我使用created_column的行进行分组。这非常简单。

查询如下:

SELECT YEAR(created_at) as year, MONTH(created_at) as month, COUNT(type) as student_count
FROM users
WHERE type = "student"
GROUP BY year, month
ORDER BY year, month

我现在需要再添加2列“订阅”和“ pay_per_video”,这将把每个月和每年的总数进一步划分为学生级别类型的“订阅”或“ pay_per_video”。例如。如果在2017年1月共有20名学生注册。每视频学生12名,而当月有8名是订阅学生。任何指针,不胜感激。

更新 我正在寻找的是这样的: 表格:Subject_Selection

Year    Month       Student Count     Pay Per View     Subscription
--------------------------------------------------------------------
2016     12              20                 20               0
2017     1               23                 12              11
2017     2               30                 10              20
2017     3                2                  1               1
2017     4               12                  2              10
2017     5               90                 40              50
2017     6               12                  0              12

3 个答案:

答案 0 :(得分:2)

使用如下条件聚合:

SELECT YEAR(created_at) as year, MONTH(created_at) as month, COUNT(type) as student_count,
count(case when student_level='subscription' then 1 end) as subscriptioncount,
count(case when student_level='pay_per_vedio' then 1 end) as pay_per_vediocount
FROM users
WHERE type = "student"
GROUP BY year, month
ORDER BY year, month

答案 1 :(得分:0)

请在下面查询您的需要。我希望它将按您的意愿执行。

SELECT YEAR(created_at) as year, MONTH(created_at) as month, student_level, 
COUNT(type) as student_count
FROM users
WHERE type = "student"
GROUP BY year, month, student_level
ORDER BY year, month, student_level

答案 2 :(得分:0)

  

我现在需要再添加2列“订阅”和“ pay_per_video”   它将进一步将每个月和每年的总数划分为   学生级别输入“订阅”或“ pay_per_video”。

在这里,我建议您仅添加一个名为level_type之类的列,该列将存储订阅或“ pay_per_video”作为值。

通过这样做,您的SQL将被优化为

SELECT year, month, COUNT(student_count), level_type FROM (SELECT YEAR(created_at) as year, MONTH(created_at) as month, COUNT(type) as student_count
FROM users
WHERE type = "student"
GROUP BY year, month
ORDER BY year, month) as s
GROUP BY level_type