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.

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 |
+------------+----+-------+------+

您可以使用 RANK(),在 dateid 上进行分区并按 value 降序排列:

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

输出:

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

此查询将 运行 在您标记问题的所有 DBMS 上。