我有一个如下所示的表结构,我希望能够检索每个公司代码具有最高值的前三个记录。
我用Google搜索,我找不到更好的方式,所以希望你们能帮助我。
顺便说一句,我在MySQL和SAP HANA中尝试这种方式。但我希望如果能够获得只有MySQL的帮助,我可以获取“HANA”的“结构”
非常感谢!
这是表格:
答案 0 :(得分:1)
在MySQL中你可以做到
无论是否模仿ROW_NUMBER()
分析函数,每组(公司)都可以获得三个记录。具有相同值的记录获得相同的排名。
SELECT company, plant, value
FROM
(
SELECT company, plant, value, @n := IF(@g = company, @n + 1, 1) rnum, @g := company
FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL) i
ORDER BY company, value DESC, plant
) q
WHERE rnum <= 3;
输出:
| COMPANY | PLANT | VALUE | |---------|-------|-------| | 1 | C | 5 | | 1 | B | 4 | | 1 | A | 3 | | 2 | G | 6 | | 2 | C | 5 | | 2 | D | 3 | | 3 | E | 8 | | 3 | A | 7 | | 3 | B | 3 |
获取每个组的所有记录,其排名为1到3,模拟DENSE_RANK()
分析函数
SELECT company, plant, value
FROM
(
SELECT company, plant, value, @n := IF(@g = company, IF(@v = value, @n, @n + 1), 1) rnum, @g := company, @v := value
FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL, @v := NULL) i
ORDER BY company, value DESC, plant
) q
WHERE rnum <= 3;
输出:
| COMPANY | PLANT | VALUE | |---------|-------|-------| | 1 | C | 5 | | 1 | B | 4 | | 1 | A | 3 | | 1 | E | 3 | | 1 | G | 3 | | 2 | G | 6 | | 2 | C | 5 | | 2 | D | 3 | | 3 | E | 8 | | 3 | A | 7 | | 3 | B | 3 | | 3 | G | 3 |
这是 SQLFiddle 演示
更新现在它看起来像HANA supports analytic functions所以查询看起来像
SELECT company, plant, value
FROM
(
SELECT company, plant, value,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY value DESC) rnum
FROM table1
)
WHERE rnum <= 3;
SELECT company, plant, value
FROM
(
SELECT company, plant, value,
DENSE_RANK() OVER (PARTITION BY company ORDER BY value DESC) rank
FROM table1
)
WHERE rank <= 3;
以下是 SQLFiddle 演示适用于Oracle,但我相信它也适用于HANA