我有第二列的表格按降序排列
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
谢谢..!
答案 0 :(得分:3)
试试这个
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
答案 1 :(得分:0)
以下是使用变量
的方法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 |
答案 2 :(得分:0)
我目前没有安装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