如何在PostgreSQL查询中选择特定的行?

时间:2015-07-06 06:17:02

标签: sql postgresql greatest-n-per-group

我写了一个查询来获取' reason_code'和' app_count'结果集中的前五行和名称'其他人的剩余app_count的总和'。

我在这里尝试过:

(SELECT a.app_pgm_rsnd_rsn_cd, a.denied_app_count
FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
FROM app_pgm_choice, ead_case 
where app_pgm_sts= 'DN'
AND app_pgm_req_dt >= '20150101'
AND app_pgm_req_dt <= '20150130'
AND EAD_CS_APP_NUM =  APP_PGM_NUM
AND EAD_CS_SEND_CNTY_ID = '19'
AND EAD_CS_TRAN_STS = 'PE'
GROUP BY app_pgm_rsnd_rsn_cd
ORDER BY denied_app_count desc) a
WHERE ROWNUM <=5 )

UNION ALL

(SELECT 'OTHERS' as app_pgm_rsnd_rsn_cd, SUM(b.denied_app_count) as    denied_app_count
FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
FROM app_pgm_choice, ead_case 
where app_pgm_sts= 'DN'
AND app_pgm_req_dt >= '20150101'
AND app_pgm_req_dt <= '20150130'
AND EAD_CS_APP_NUM =  APP_PGM_NUM
AND EAD_CS_SEND_CNTY_ID = '19'
AND EAD_CS_TRAN_STS = 'PE'
GROUP BY app_pgm_rsnd_rsn_cd
ORDER BY denied_app_count desc) b
WHERE ROWNUM >=5 )

但是当我运行此查询时,它会显示以下错误消息:

  

错误:专栏&#34; rownum&#34;不存在      第13行:在哪里ROWNUM&lt; = 5)                ^

     

**********错误**********

     

错误:专栏&#34; rownum&#34;不存在     SQL状态:42703     性格:397

ROWNUM变量的选项是什么?

2 个答案:

答案 0 :(得分:4)

我认为您正在寻找LIMIT条款。

SELECT * 
FROM sometable 
ORDER BY denied_app_count DESC
LIMIT 5

ROWNUM是Oracle主义。

对于大于号,您可以使用OFFSET

SELECT * 
FROM sometable 
ORDER BY denied_app_count DESC
OFFSET 5

跳过前5行并返回其余部分。

在做分页等事情时,这两者可以合并,而且往往是合并的。

请参阅LIMIT and OFFSET

在PostgreSQL中你可以使用row_number()窗口函数,但是为了你的目的,这是不必要的。另一方面,使用row_number执行单个查询可能更快,然后查询结果表两次以获得这两个部分。尝试这种方法,看看它是否表现更好。

答案 1 :(得分:1)

尝试此查询

(SELECT a.app_pgm_rsnd_rsn_cd, a.denied_app_count
FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
,row_number() OVER (ORDER BY app_pgm_rsnd_rsn_cd ) AS ROWNUM 
FROM app_pgm_choice, ead_case 
where app_pgm_sts= 'DN'
AND app_pgm_req_dt >= '20150101'
AND app_pgm_req_dt <= '20150130'
AND EAD_CS_APP_NUM =  APP_PGM_NUM
AND EAD_CS_SEND_CNTY_ID = '19'
AND EAD_CS_TRAN_STS = 'PE'
GROUP BY app_pgm_rsnd_rsn_cd
ORDER BY denied_app_count desc) a
WHERE ROWNUM <=5 )

UNION ALL

(SELECT 'OTHERS' as app_pgm_rsnd_rsn_cd, SUM(b.denied_app_count) as    denied_app_count
FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
,row_number() OVER (ORDER BY app_pgm_rsnd_rsn_cd ) AS ROWNUM 
FROM app_pgm_choice, ead_case 
where app_pgm_sts= 'DN'
AND app_pgm_req_dt >= '20150101'
AND app_pgm_req_dt <= '20150130'
AND EAD_CS_APP_NUM =  APP_PGM_NUM
AND EAD_CS_SEND_CNTY_ID = '19'
AND EAD_CS_TRAN_STS = 'PE'
GROUP BY app_pgm_rsnd_rsn_cd
ORDER BY denied_app_count desc) b
WHERE ROWNUM >=5 )