嗨,我发现很难实现Rank()函数,下面是我的示例表
id category value volume
1 product1 0.4 0.5
2 product2 0.9 0.6
3 product3 0.3 0.7
4 product4 0.19 0.59
现在我想分别给列“值”和“音量”排名并获得每列的前3和后3,我在firefox浏览器sqlmanager中测试下面的代码。但查询无效。
SELECT Value, RANK()
OVER (ORDER BY Value DESC) AS xRank
FROM (SELECT Value FROM product_achievment) WHERE xRank>=3;
感谢任何帮助。
答案 0 :(得分:0)
RANK
。UNION
有四个不同的查询。因此,以下查询将返回所需的行:
SELECT * FROM product_achievement ORDER BY value LIMIT 3
UNION
SELECT * FROM product_achievement ORDER BY value DESC LIMIT 3
UNION
SELECT * FROM product_achievement ORDER BY volume LIMIT 3
UNION
SELECT * FROM product_achievement ORDER BY volume DESC LIMIT 3;
RANK
的解决方法:
如果您还需要排名信息,我建议您创建一个排名为VIEW
:
CREATE VIEW ranked_product_achievement AS
SELECT *,
(SELECT COUNT() FROM product_achievement WHERE value<=t.value) AS r_value_a,
(SELECT COUNT() FROM product_achievement WHERE value>=t.value) AS r_value_d,
(SELECT COUNT() FROM product_achievement WHERE volume<=t.volume) AS r_volume_a,
(SELECT COUNT() FROM product_achievement WHERE volume>=t.volume) AS r_volume_d
FROM product_achievement AS t;
然后你可以从创建的视图中SELECT
:
SELECT id, category, value, volume, r_value_a, r_volume_a
FROM ranked_product_achievement
WHERE r_value_a<=3 OR r_value_d<=3 OR r_volume_a<=3 OR r_volume_d<=3;