Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

sql - SQL查询/根据日期和ID计算值的等级(Sql Query / Calculate rank for values based on date and id)

For each date and id we have to give the rank to values in decreasing order.

(对于每个日期和ID,我们必须按降序对值进行排名。)

Below is the Input Table.

(下面是输入表。)

>input data
+------------+----+-------+
|    date    | id | value |
+------------+----+-------+
| 01-01-2018 | A  |    20 |
| 01-01-2018 | A  |    50 |
| 01-01-2018 | C  |    40 |
| 01-01-2018 | B  |    40 |
| 02-01-2018 | A  |    30 |
| 03-01-2018 | C  |    20 |
| 03-01-2018 | C  |    40 |
| 04-01-2018 | B  |     0 |
| 04-01-2018 | B  |    40 |
| 05-01-2018 | B  |    70 |
+------------+----+-------+

Output should look like below:

(输出应如下所示:)

>output data
+------------+----+-------+------+
|    date    | id | value | rank |
+------------+----+-------+------+
| 01-01-2018 | A  |    50 |    1 |
| 01-01-2018 | A  |    20 |    2 |
| 01-01-2018 | B  |    40 |    1 |
| 01-01-2018 | C  |    40 |    1 |
| 02-01-2018 | A  |    30 |    1 |
| 03-01-2018 | C  |    40 |    1 |
| 03-01-2018 | C  |    20 |    2 |
| 04-01-2018 | B  |    40 |    1 |
| 04-01-2018 | B  |     0 |    2 |
| 05-01-2018 | B  |    70 |    1 |
+------------+----+-------+------+
  ask by Akash Jain translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use RANK() , partitioning on date and id and ordering by value descending:

(您可以使用RANK() ,对dateid分区,并按value降序排序:)

SELECT *,
       RANK() OVER (PARTITION BY date, id ORDER BY value DESC) AS ranking
FROM data

Output:

(输出:)

date        id  value   ranking
01-01-2018  A   50      1
01-01-2018  A   20      2
01-01-2018  B   40      1
01-01-2018  C   40      1
02-01-2018  A   30      1
03-01-2018  C   40      1
03-01-2018  C   20      2
04-01-2018  B   40      1
04-01-2018  B   0       2
05-01-2018  B   70      1

Demo on SQLFiddle

(关于SQLFiddle的演示)

This query will run on all the DBMS you have tagged your question with.

(该查询将在您标记了问题的所有DBMS上运行。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...