`user` varchar(10),
`fruit` varchar(10),
`money` int
)
INSERT INTO test
SELECT 'user1', 'banana', 60 UNION ALL
SELECT 'user1', 'Apple', 1981 UNION ALL
SELECT 'user1', 'watermelon', 4080 UNION ALL
SELECT 'user1', 'Apple', 622 UNION ALL
SELECT 'user2', 'banana', 122246 UNION ALL
SELECT 'user2', 'Apple', 369 UNION ALL
SELECT 'user2', 'watermelon', 57362 UNION ALL
SELECT 'user3', 'banana', 463 UNION ALL
SELECT 'user3', 'watermelon', 11382 UNION ALL
SELECT 'user3', 'Apple', 966
SELECT
CASE
WHEN @user != test.`user` THEN @rownum:= 1
ELSE @rownum:= @rownum + 1
END AS No,
@user := test.`user` AS `User`,
test.`fruit`,
test.`money`
FROM
(SELECT @rownum:=0) r,
(SELECT @user:='') p,
test
ORDER BY
test.`user`,
test.`money` DESC
因为本机 MySQL 编码问题, 就把 中文给 修改成 英文了。
执行结果如下:
mysql> SELECT-> CASE
-> WHEN @user != test.`user` THEN @rownum:= 1
-> ELSE @rownum:= @rownum + 1
-> END AS No,
-> @user := test.`user` AS `User`,
-> test.`fruit`,
-> test.`money`
-> FROM
-> (SELECT @rownum:=0) r,
-> (SELECT @user:='') p,
-> test
-> ORDER BY
-> test.`user`,
-> test.`money` DESC
->
+------+-------+------------+--------+
| No | User | fruit | money |
+------+-------+------------+--------+
| 1 | user1 | watermelon | 4080 |
| 2 | user1 | Apple | 1981 |
| 3 | user1 | Apple | 622 |
| 4 | user1 | banana | 60 |
| 1 | user2 | banana | 122246 |
| 2 | user2 | watermelon | 57362 |
| 3 | user2 | Apple | 369 |
| 1 | user3 | watermelon | 11382 |
| 2 | user3 | Apple | 966 |
| 3 | user3 | banana | 463 |
+------+-------+------------+--------+
10 rows in set (0.00 sec)
mysql>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)