我有第二列的表按降序排列
a 30
a 28
a 18
a 10
b 40
b 34
c 32
c 22
我想要这样的结果
a 30 1
a 28 2
a 18 3
a 10 4
b 40 1
b 34 2
c 32 1
c 22 2
谢谢..!
我有第二列的表按降序排列
a 30
a 28
a 18
a 10
b 40
b 34
c 32
c 22
我想要这样的结果
a 30 1
a 28 2
a 18 3
a 10 4
b 40 1
b 34 2
c 32 1
c 22 2
谢谢..!
尝试这个
SELECT t1.*, COUNT(*) AS rank
FROM Table1 t1
INNER JOIN
Table1 t2 on t1.col1 = t2.col1
AND t1.col2 <= t2.col2
GROUP BY t1.col1, t1.col2
ORDER BY t1.col1, t1.col2 DESC
这是使用变量的方法
SET @level:=1;
SET @group='';
SELECT
column1,
column2,
Sort
FROM(
SELECT
column1,
column2,
@level :=(IF(@group = column1,@level+1 ,1)) AS `Sort`,
@group := column1
FROM t
ORDER BY column1 ASC, column2 DESC
) AS l;
输出
| COLUMN1 | COLUMN2 | SORT |
----------------------------
| a | 30 | 1 |
| a | 28 | 2 |
| a | 18 | 3 |
| a | 10 | 4 |
| b | 40 | 1 |
| b | 34 | 2 |
| c | 32 | 1 |
| c | 22 | 2 |
我目前没有安装 mysql 但应该有等效的,甚至这可能有效:
SELECT
a, b, row_number() OVER (PARTITION BY a ORDER BY a ASC, b DESC)
FROM test GROUP BY a, b ORDER BY a ASC, b DESC;
适用于 postgresql 9.2