0

嗨,我发现很难实现 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 

现在我想分别对列“value”和“volume”进行排名,并获得每列的前 3 名和后 3 名,我在 firefox 浏览器 sqlmanager 中测试下面的代码。但查询不起作用。

SELECT Value, RANK() 
OVER (ORDER BY Value DESC) AS xRank 
FROM (SELECT Value FROM product_achievment) WHERE xRank>=3;

任何帮助表示赞赏。

4

1 回答 1

0
  1. 不是不支持RANK
  2. 您必须有四个不同的查询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

如果您还需要排名信息,我建议创建一个VIEWwith 排名:

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;
于 2013-10-03T08:45:09.307 回答