Oracle sql中的rownum with group by

时间:2017-12-19 13:52:48

标签: oracle date group-by row-number

我需要构建一个查询来按成员检索信息组和到期日期,但我需要为每个成员提供一个序列号..

例如:

如果会员“A”有3条记录到期,“B”只有1条而“C”有2条,我需要这样的结果:

Number    Member  ExpDate
 1           A    01/01/2020
 2           A    02/01/2020
 3           A    03/01/2020
 1           B    01/01/2020
 1           C    01/01/2020
 2           C    02/01/2020

我的查询现在是:

SELECT ROW_NUMBER() OVER(ORDER BY TRUNC(EXPIRATION_DT) ASC) AS SEQUENCE, MEMBER_ID AS MEMBER, SUM(ACCRUALED_VALUE) - SUM(USED_VALUE) AS POINTS, trunc(EXPIRATION_DT) AS EXPDATE
FROM TABLE1
WHERE EXPIRATION_DT > SYSDATE AND  EXPIRATION_DT < SYSDATE + 90
GROUP BY MEMBER_ID, TRUNC(EXPIRATION_DT)
HAVING SUM(ACCRUALED_VALUE) - SUM(USED_VALUE) > 0
ORDER BY 4 ASC;

但我不能“分组”序列号....结果现在是:

Seq Mem Points Date
1   1-O  188   2018-03-01 00:00:00
2   1-C  472   2018-03-01 00:00:00
3   1-A  485   2018-03-01 00:00:00
4   1-1  267   2018-03-01 00:00:00
5   1-E  500   2018-03-01 00:00:00
6   1-P  55    2018-03-01 00:00:00
7   1-E  14    2018-03-01 00:00:00

2 个答案:

答案 0 :(得分:3)

我认为你需要一个DENSE_RANK窗口函数。试试这个 -

 SELECT DENSE_RANK() OVER (PARTITION BY MEMBER ORDER BY TRUNC(EXPIRATION_DT) ASC) AS SEQUENCE
       ,MEMBER_ID AS MEMBER
       ,SUM(ACCRUALED_VALUE) - SUM(USED_VALUE) AS POINTS
       ,trunc(EXPIRATION_DT) AS EXPDATE
FROM TABLE1
WHERE EXPIRATION_DT > SYSDATE AND  EXPIRATION_DT < SYSDATE + 90
GROUP BY MEMBER_ID
        ,TRUNC(EXPIRATION_DT)
HAVING SUM(ACCRUALED_VALUE) - SUM(USED_VALUE) > 0
ORDER BY 4 ASC;

答案 1 :(得分:1)

with g as (
select *
From TABLE1 g
group by MEMBER_ID
        ,TRUNC(EXPIRATION_DT)
HAVING SUM(ACCRUALED_VALUE) - SUM(USED_VALUE) > 0   ---- etc
) 
select rownum, g.* From g

此选择返回具有序列号的第一列