分析函数:ROW_NUMBER()

时间:2018-11-21 11:07:57

标签: sql oracle window-functions

我有一个表格“发票”

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 TOTAL 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 TOTAL 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列数据不匹配。

2 个答案:

答案 0 :(得分:3)

您接近了,您可能需要按row_number顺序订购id(假设它是根据时间升序的)

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)

答案 1 :(得分:0)

我在查询中未找到任何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