繁体   English   中英

SQL查询以查找运行总计中的数字计数

[英]SQL query to find counts of numbers in running total

假设该表具有1列ID,其值如下:

ID
5
5
5
6
5
5
6
6

输出应该是

ID  count
5    3
6    1
5    2
6    2

我们如何在单个SQL查询中做到这一点。

如果要查找记录的总数,可以这样写:

按column_name从database_name顺序选择count(*);

在关系数据库中,表中的数据没有任何顺序,请参见: https : //en.wikipedia.org/wiki/Table_( database

除非在查询表的SELECT语句中指定了ORDER BY子句,否则数据库系统不保证行的任何顺序。

因此,为了获得理想的结果,您必须在表中具有一个附加的列,该列定义行的顺序(并且可以在ORDER BY子句中使用)。


在下面的示例cn列中定义了这样的顺序:

select * from tab123 ORDER BY rn;

        RN ID 
---------- -------
         1 5 
         2 5
         3 5 
         4 6 
         5 5 
         6 5
         7 6
         8 6  

从Oracle版本12c开始,可以使用新的MATCH_REGOGNIZE子句:

select * from tab123 
match_recognize(
   order by rn
   measures
     strt.id as id,
     count(*) as cnt
   one row per match
   after match skip past last row
   pattern( strt ss* )
   define ss as ss.id = prev( ss.id )
);

在支持Windows功能的早期版本(Oracle 10及更高版本)上,可以使用两种Windows功能: LAG ... overSUM ... over ,以这种方式

select max( id ) as id, count(*) as cnt
FROM (
    select id, sum( xxx ) over (order by rn ) as yyy
    from (
        select t.*,
               case lag( id ) over (order by rn )
               when id then 0 else 1 end as xxx
        from tab123 t
    )
)
GROUP BY yyy
ORDER BY yyy;

暂无
暂无

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

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