我要计算到现在为止进行的期间总数? 以下是我数据库的结构。.一个部分(选修课)一次可以有两个科目
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
如何修改查询,以便获得上述结果?
答案 0 :(得分:1)
删除Group BY
并将date
和period
合并到您的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"
已更新
SELECT COUNT(Distinct period, date) 'noofper'
FROM testtable
WHERE section ='A' AND date <= "2020-01-08"
答案 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