使用group by子句检索的记录总和

时间:2020-01-08 10:44:32

标签: mysql sql group-by

我要计算到现在为止进行的期间总数? 以下是我数据库的结构。.一个部分(选修课)一次可以有两个科目

section  period  subject     date
------------------------------------
A        1       SUB1     2020-01-07
A        2       E1       2020-01-07
A        2       E2       2020-01-07
A        3       SUB2     2020-01-07
A        4       SUB3     2020-01-07
A        5       SUB4     2020-01-07
A        1       SUB4     2020-01-08
A        2       SUB2     2020-01-08
A        3       E1       2020-01-08
A        3       E2       2020-01-08
A        4       SUB1     2020-01-08
A        5       SUB3     2020-01-08

我使用了如下查询:

select count(distinct period) 'noofper' 
from testtable 
where section='A' 
and date<="2020-01-08" 
group date

我得到的结果是

noofper
--------
5
5

我希望结果为

noofper
-------
10

如何修改查询,以便获得上述结果?

2 个答案:

答案 0 :(得分:1)

删除Group BY并将dateperiod合并到您的Count

SELECT COUNT(Distinct CONCAT(CAST(period AS CHAR),CAST(DAYOFYEAR(date) AS CHAR))) 'noofper' 
FROM testtable 
WHERE section ='A' AND date <= "2020-01-08" 

DB FIDDLE

已更新

SELECT COUNT(Distinct period, date) 'noofper' 
FROM testtable 
WHERE section ='A' AND date <= "2020-01-08" 

FIDDLE DEMO

答案 1 :(得分:0)

您可以使用不带组的和

    select count(distinct period) 'noofper' from testtable where section='A' and date<="2020-01-08" 

如果您可以使用其他逻辑,则可以使用subquery + sum来完成

select sum('noofper') 'noofper' 
from (
    select count(distinct period) 'noofper' from testtable where section='A' and date<="2020-01-08" group date
    /*some logic*/
) T

和结果:

noofper
-------
10
相关问题