选择截至日期的行数

时间:2018-05-24 11:22:00

标签: mysql sql

列出像:

这样的人
name      date_of_birth
john      1987-09-08
maria     1987-09-08
samuel    1987-09-09
claire    1987-09-10
jane      1987-09-10
rose      1987-09-12
...

如何使用SQL获取结果视图,了解该日期之前有多少人出生,例如该表的输出应为:

date        count
1987-09-08  2
1987-09-09  3
1987-09-10  5
1987-09-11  5
1987-09-12  6
...

谢谢!

3 个答案:

答案 0 :(得分:4)

一种方法是相关子查询:

select dob.date_of_birth,
       (select count(*) from t where t.date_of_birth <= dob.date_of_birth) as running_count
from (select distinct date_of_birth from t) dob;

这不是特别有效。如果您的数据有任何大小,则变量更好(或者如果您使用的是MySQL 8.0,则为窗口函数):

select date_of_birth,
       (@x := @x + cnt) as running_count
from (select date_of_birth, count(*) as cnt
      from t
      group by date_of_birth
      order by date_of_birth
     ) dob cross join
     (select @x := 0) params;

答案 1 :(得分:4)

除了戈登的回答,这是另一种方式。它使用连接:

SELECT
    t1.date_of_birth,
    COUNT(*) AS count
FROM (SELECT DISTINCT date_of_birth FROM yourTable) t1
INNER JOIN yourTable t2
    ON t1.date_of_birth >= t2.date_of_birth
GROUP BY
    t1.date_of_birth;

注意:我遗漏了一步。显然你也想报告错过的日期。如果是这样,那么您可以用日历表替换我作为t1别名的内容。为了演示,您可以内联所有日期:

SELECT
    t1.date_of_birth,
    COUNT(*) AS count
FROM
(
    SELECT '1987-09-08' AS date_of_birth UNION ALL
    SELECT '1987-09-09' UNION ALL
    SELECT '1987-09-10' UNION ALL
    SELECT '1987-09-11' UNION ALL
    SELECT '1987-09-12'
) t1
LEFT JOIN yourTable t2
    ON t1.date_of_birth >= t2.date_of_birth
GROUP BY
    t1.date_of_birth;

enter image description here

Demo

实际上,您的日历表将是一个真实的表格,其中只包含您希望在结果集中显示的所有日期。

答案 2 :(得分:0)

使用subquery相关方法:

select date_of_birth, (select count(*)
                       from table
                       where date_of_birth <= t.date_of_birth
                       ) as count
from table t
group by date_of_birth;