我有一个SQLite数据库,如下所示:
id | num1 | num2 | value
---|------|------|------
1 | 2 | 1 | "foo"
2 | 1 | 1 | "foo"
3 | 2 | 4 | "foo"
4 | 2 | 3 | "foo"
5 | 1 | 1 | "foo"
6 | 1 | 1 | "foo"
7 | 1 | 3 | "foo"
8 | 1 | 2 | "foo"
我需要选择以下内容:
num1
和num2
num1
排序的num2
/ num1
组合排名然后num2
结果表应该如下所示:
id | num1 | num2 | value | num | rank
---|------|------|-------|-----|-----
1 | 2 | 1 | "foo" | 6 | 4
2 | 1 | 1 | "foo" | 6 | 1
3 | 2 | 4 | "foo" | 6 | 6
4 | 2 | 3 | "foo" | 6 | 5
5 | 1 | 1 | "foo" | 6 | 1
6 | 1 | 1 | "foo" | 6 | 1
7 | 1 | 3 | "foo" | 6 | 3
8 | 1 | 2 | "foo" | 6 | 2
我尝试了很多不同的子查询,但没有得到任何有用的结果。
编辑:我设法使用以下查询获得组合数(所以列num
):
SELECT
*,
(
SELECT count (*)
FROM ( SELECT DISTINCT num1, num2
FROM table)
)
AS num
FROM table;
答案 0 :(得分:1)
可以通过计算等于或小于当前行的不同行来计算等级。
如果num1
较小,或者num1
相等且num2
较小,则行较小。
...,
(SELECT COUNT(*)
FROM (SELECT DISTINCT num1, num2
FROM MyTable) AS T2
WHERE T2.num1 < MyTable.num1
OR (T2.num1 = MyTable.num1 AND
T2.num2 <= MyTable.num2)
) AS num,
...