如何根据分数设置排名

时间:2016-08-04 19:22:29

标签: sql

我有这样的查询

SELECT     CJ.JOURNAL_ID AS JOURNAL_ID, 
           VOLUME,
           ISSUE,
           PAPER_ID,
           COUNT(PAPER_ID) AS PAPER_COUNT
FROM       cafet_paper_details CPD 
INNER JOIN CAFET_JOURNAL       CJ  ON  CJ.JOURNAL_ID = CPD.JOURNAL_ID  
GROUP BY   JOURNAL_ID,VOLUME, ISSUE
ORDER BY   JOURNAL_ID,VOLUME

给了我以下结果

JOURNAL_ID  VOLUME  ISSUE   PAPER_ID  PAPER_COUNT  
----------  ------  ------  --------  -------------
        18  2008    04            33             18
        18  2009    05            46              3
        18  2012    03            10             22
        19  2016    1              9              1

从上表中我想添加一个基于ASC VOLUME的列'VOLUME_RANK'(对于2008卷,我应该将volume_rank设为1,2009年为2,2010为3,依此类推)

预期产出

JOURNAL_ID  VOLUME  ISSUE   PAPER_ID  PAPER_COUNT   VOLUME_RANK
----------  ------  ------  --------  ------------- ------------
        18  2008    04            33             18     1
        18  2009    05            46              3     2
        18  2012    03            10             22     5
        19  2016    1              9              1     9

3 个答案:

答案 0 :(得分:1)

SELECT CJ.JOURNAL_ID AS JOURNAL_ID,
   VOLUME,
   (VOLUME -2007) VOLUME_RANK ISSUE,
                              PAPER_ID,
                              COUNT(PAPER_ID) AS PAPER_COUNT

FROM cafet_paper_details CPD INNER JOIN CAFET_JOURNAL CJ ON CJ.JOURNAL_ID = CPD.JOURNAL_ID GROUP BY JOURNAL_ID,          体积,          问题 ORDER BY JOURNAL_ID,          VOLUME

答案 1 :(得分:0)

根据您的描述,您似乎想要简单的减法:

SELECT CJ.JOURNAL_ID, VOLUME, ISSUE, PAPER_ID,
       COUNT(PAPER_ID) AS PAPER_COUNT,
       (VOLUME - 2007) as VOLUME_RANK
FROM cafet_paper_details CPD INNER JOIN
     CAFET_JOURNAL CJ
     ON CJ.JOURNAL_ID = CPD.JOURNAL_ID  
GROUP BY JOURNAL_ID, VOLUME, ISSUE
ORDER BY JOURNAL_ID, VOLUME;

答案 2 :(得分:0)

with view1 as 
(SELECT     CJ.JOURNAL_ID AS JOURNAL_ID, 
       VOLUME,
       ISSUE,
       PAPER_ID,
       COUNT(PAPER_ID) AS PAPER_COUNT
FROM       cafet_paper_details CPD 
INNER JOIN CAFET_JOURNAL       CJ  ON  CJ.JOURNAL_ID = CPD.JOURNAL_ID  
GROUP BY   JOURNAL_ID,VOLUME, ISSUE
ORDER BY   JOURNAL_ID,VOLUME
),
view2 as (
select JOURNAL_ID, VOLUME, ISSUE, PAPER_ID, PAPER_COUNT, (select min(volume)         from view1) from view1 MIN_VOLUME
)
select JOURNAL_ID, VOLUME, ISSUE, PAPER_ID, PAPER_COUNT, MIN_VOLUME, (VOLUME-MIN_VOLUME + 1) rank from view2