假设我有一个如下表(我正在使用Oracle 10g btw)
NAME VALUE
------ ------
BOB 1
BOB 2
BOB 4
SUZY 1
SUZY 2
SUZY 3
如何选择value
最接近但不大于给定数字的所有行。例如,如果我想找到值最接近3的所有行,我会得到:
NAME VALUE
------ ------
BOB 2
SUZY 3
这似乎应该很简单......但我没有运气。
谢谢!
答案 0 :(得分:4)
SELECT name, max(value)
FROM tbl
WHERE value <= 3
GROUP BY name
答案 1 :(得分:1)
这有效(SQLFiddle demo):
SELECT name, max(value)
FROM mytable
WHERE value <= 3
GROUP BY name
答案 2 :(得分:1)
基于hagensofts回答:
SELECT name, max(value)
FROM tbl
WHERE value <= 3 AND ROWNUM <=2
GROUP BY name
使用ROWNUM可以限制输出行,所以如果你想要2行,那么你可以限制rownum。
答案 3 :(得分:0)
WITH v AS (
SELECT 'BOB' NAME, 1 value FROM dual
UNION ALL
SELECT 'BOB', 2 FROM dual
UNION ALL
SELECT 'BOB', 4 FROM dual
UNION ALL
SELECT 'SUZY', 1 FROM dual
UNION ALL
SELECT 'SUZY', 2 FROM dual
UNION ALL
SELECT 'SUZY', 3 FROM dual
)
SELECT *
FROM v
WHERE (name, value) IN (SELECT name, MAX(value)
FROM v
WHERE value <= :num
GROUP BY name)
;