如果我有tblCust
c_id Option Numbers
10 1 2
5 1 1
10 2 1
我想返回数字最大的选项c_id = 10.我已经尝试了
SELECT Option, MAX(Numbers) FROM tblCust WHERE c_id = 10
但没有运气
答案 0 :(得分:1)
您没有指定DBMS,因此这是标准SQL
select *
from (
select c_id,
option,
max(option) over (partition by c_id) as max_opt
from tblCust
where c_id = 10
) t
where option = max_opt;
答案 1 :(得分:1)
如果没有子查询,您可以对事物进行排序以获得最大的
SELECT Option FROM tblCust
WHERE c_id = 10
ORDER BY Number DESC LIMIT 1
答案 2 :(得分:0)
使用此:
SELECT Option, Numbers
FROM tblCust
WHERE c_id = 10
ORDER BY Numbers DESC
LIMIT 1
输出:
Option Numbers
1 2
答案 3 :(得分:0)
我认为max()over()的使用是针对Numbers而不是Option
select *
from (
select c_id,
option,
max(numbers) over (partition by c_id) as max_numbers
from tblCust
where c_id = 10
) t
where numbers = max_numbers;
但是,如果数据中有多条记录等于max(Numbers) - 并且您只想要一条结果记录 - 那么使用row_number()可能是更好的选择。
select *
from (
select c_id,
option,
row_number() over (partition by c_id order by Numbers DESC, Option DESC) as rn
from tblCust
where c_id = 10
) AS t
where rn=1
;
注意在此处的over()内的顺序,它首先放置最高的数字和选项,然后给出row_number值为1