在我的表中,我记录了各种信息,但是这个问题的关键字段是subject_id和lesson_time,我想按主题分组,给出每个主题的每一天的总行数和总行数对于每个主题(每周总数),所以从这个样本数据:
id subject_id lesson_time
1 4 2015-04-28
2 4 2015-04-28
3 3 2015-04-28
4 1 2015-04-28
5 4 2015-04-27
我想计算星期一到星期五和星期总数的每个主题的总数,因此上述数据示例的输出将为:
subject_id monday_total tuesday_total wednesday_total ... week_total
1 0 1 0 1
3 0 1 0 1
4 1 2 0 3
我可以通过主题轻松获得总数,因为它只是在分组后计数(*),我正在努力的是每个日期的计数,我当前(非工作)查询
SELECT
subject_id,
COUNT( DAYOFWEEK(lesson_time)=2) AS monday_total,
COUNT( DAYOFWEEK(lesson_time)=3) AS tuesday_total,
COUNT( DAYOFWEEK(lesson_time)=4) AS wednesday_total,
COUNT( DAYOFWEEK(lesson_time)=5) AS thursday_total,
COUNT( DAYOFWEEK(lesson_time)=6) AS friday_total,
COUNT(*) AS week_total
FROM
tbl_lessons
GROUP BY
subject_id
非常感谢任何帮助。
答案 0 :(得分:2)
试试这个
SELECT
subject_id,
SUM(DAYOFWEEK(lesson_time)=2) AS monday_total,
SUM(DAYOFWEEK(lesson_time)=3) AS tuesday_total,
SUM(DAYOFWEEK(lesson_time)=4) AS wednesday_total,
SUM(DAYOFWEEK(lesson_time)=5) AS thursday_total,
SUM(DAYOFWEEK(lesson_time)=6) AS friday_total,
COUNT(*) AS week_total
FROM
tbl_lessons
GROUP BY
subject_id
在mysql中COUNT(n)
计算每一行(n
不是NULL
的每一行都为+1)。 SUM(n)
将所有n
值相加(每行+ n
)。
当布尔表达式返回1或0时,SUM(DAYOFWEEK(lesson_time)=2)
将返回DAYOFWEEK(lesson_time)=2
的行数(它就像汇总布尔值1 + 0 + 0 + 1 + 1 + 1 + 0 + 0 1 + ...)
答案 1 :(得分:-1)
SELECT date(lesson_time) AS lesson_time, count( * ) AS count FROM tbl_lessons GROUP BY date(lesson_time)