繁体   English   中英

分析函数:ROW_NUMBER()

[英]Analytic Function: ROW_NUMBER( )

我有一张表格“发票”

id integer Primary key
customer_id Integer
total Number (*,2)

该查询将向别名为“ SNO”的每个客户显示所有的customer_id,总数和运行序列号。 并且记录应基于customer_id然后由SNO以升序显示。

提示:

  • 分析函数:ROW_NUMBER()
  • 分析条款:query_partition_clause和order_by_clause。

我写了以下查询:

Select customer_id,
       total,
       ROW_NUMBER( ) OVER (PARTITION BY customer_id ORDER BY customer_id ASC) AS "SNO"
from invoice;

但是结果失败了。 我想念的是什么。 也就是所谓的“记录应基于customer_id 然后按SNO升序显示”。

我得到的结果如下:
CUSTOMER_ID总计SNO
1 70000 1
2 250000 1
2 560000 2
3 200000 1
3 45000 2
4 475000 1
5 50000 1
5 10000 2
6 600000 1
6 90000 2

预期结果是:
CUSTOMER_ID总计SNO
1 70000 1
2 250000 1
2 560000 2
3 45000 1
3 200000 2
4 475000 1
5 10000 1
5 50000 2
6 600000 1
6 90000 2
TOTAL列数据不匹配。

您接近了,您可能需要按idrow_number进行排序(假设它根据时间升序)

Select customer_id,
       total,
       ROW_NUMBER( ) OVER (PARTITION BY customer_id ORDER BY id ASC) AS "SNO"
from invoice
order by customer_id, "SNO" -- should be the default anyway (but there's no guarantee)

我在您的查询中未找到任何order by子句,这是您要生成SNO的哪个问题? 通过使用idtotal会影响您的订购

 with cte as
(
select  1  cid, 70000  total from dual
    union all
select 2, 250000 from dual
    union all
select 2, 560000 from dual
union all
select 3, 200000 from dual
    union all
select 3, 45000  from dual
    union all
select 4, 475000 from dual
union all
select 5, 50000 from dual
union all
select 5, 10000 from dual
union all
select 6, 600000 from dual
union all
select 6, 90000 from dual

)Select cid,total,ROW_NUMBER( ) OVER (PARTITION BY cid ORDER BY total ) AS "SNO" from cte order by cid,SNO

暂无
暂无

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

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