简体   繁体   English

按星期几和每个主题的星期总数计算总数

[英]Count Totals by Day of Week and Week Total for each Subject

In my table I have recorded various bits of information but the key fields for this problem are the subject_id and lesson_time where I want to group by subject to give a total count of rows for each day of week for each subject and total rows for each subject(weekly total), so from this sample data: 在我的表格中,我记录了各种各样的信息,但是此问题的关键字段是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

I want to count the totals for each subject for monday to friday and week total, so output for the above data example would be: 我想计算周一至周五和周总计的每个主题的总计,因此上述数据示例的输出为:

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

I can get total by subject easy enough as it is just count(*) after group by, what I am struggling with is the count for each individual day, my current (non working) query is 我可以很容易地按主题获得总数,因为它只是分组之后的count(*),我正在努力的是每一天的计数,我当前的(无效)查询是

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

Any help would be much appreciated. 任何帮助将非常感激。

try this 尝试这个

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

In mysql COUNT(n) counts every row (+ 1 for every row where n is not NULL ). 在mysql中, COUNT(n)对每一行计数(对于n不为NULL每一行,则为+1)。 SUM(n) sums all n values (+ n for every row). SUM(n)将所有n值相加(每行+ n )。

As boolean expression returns 1 or 0 SUM(DAYOFWEEK(lesson_time)=2) will return number of rows where DAYOFWEEK(lesson_time)=2 (it's like summing booleans 1+0+0+1+1+1+0+0+1+...) 由于布尔表达式返回1个或0 SUM(DAYOFWEEK(lesson_time)=2)将返回的行数,其中DAYOFWEEK(lesson_time)=2 (它像求和布尔1 + 0 + 0 + 1 + 1 + 1 + 0 + 0 + 1 + ...)

SELECT date(lesson_time) AS lesson_time, count( * ) AS count FROM tbl_lessons GROUP BY date(lesson_time)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM