[英]get id where price is max in mysql
id code batch price qty
---|----- |----- |-----|---------
1 | 107 | 1 | 39 | 399
2 | 107 | 1 | 39 | 244
3 | 107 | 2 | 40 | 555
4 | 108 | 1 | 70 | 300
5 | 108 | 2 | 60 | 200
6 | 109 | 2 | 50 | 500
7 | 109 | 2 | 50 | 600
8 | 110 | 2 | 75 | 700
我想要的结果是(我希望将此结果作为输出)
id code batch price
---|----- |----- |-----|
3 | 107 | 2 | 40 |
4 | 108 | 1 | 70 |
3 | 109 | 2 | 50 |
8 | 110 | 2 | 75 |
我写这个查询
SELECT `id`,`code`,`batch` max(`price`) FROM `table_name` where `qty` > 0 group by `code`
我的输出是
id code batch price
---|----- |----- |-----|
1 | 107 | 1 | 40 |
4 | 108 | 1 | 70 |
6 | 109 | 2 | 50 |
8 | 110 | 2 | 75 |
我需要价格最高的编号和批次
获得每组最高记录的另一种方法
select *
from demo a
where (
select count(*)
from demo b
where a.code = b.code
and case when a.price = b.price then a.id < b.id else a.price < b.price end
) = 0
我假设id是自动递增的,因此,如果各组的最高价格
CASE
,您可以使用CASE
选择最新的id
您可以对按代码分组的最大值使用join
select a.id, a.code, a.batch, b.max_price
from table_name a
inner join (
select code, max(price) as max_price
from table_name
group by code
) b on a.code = b.code and a.price = b.max_price
并且如果您有更多使用相同代码的行,则可以使用价格
select max(a.id), a.code, a.batch, b.max_price
from table_name a
inner join (
select code, max(price) as max_price
from table_name
group by code
) b on a.code = b.code and a.price = b.max_price
group by a.code, a.batch, b.max_price
按价格排序,然后将结果限制为1 :)
SELECT id, batch
FROM table_name
ORDER BY price DESC
LIMIT 1
通过给行号组code
和从高到低的顺序price
列。 然后选择行号为1的行。
询问
select t1.`id`, t1.`code`, t1.`batch`, t1.`price` from (
select `id`, `code`, `batch`, `price`, (
case `code` when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := `code` end
) as `rn`
from `MyTable` t,
(select @curRow := 0, @curA := '') r
order by `code`, `price` desc
)t1
where t1.`rn` = 1
order by `code`;
Find a demo here
select id,batch from table_name order by price desc limit 0,1
尝试这个:
SELECT `id`,`code`,`batch`, `price`
FROM `table_name`
WHERE `qty` > 0
GROUP BY `code` HAVING `price` = max(`price`)
尝试这个
SELECT MAX( price
)AS价格, id
, batch
FROM table_name
我不明白您需要单个结果还是多个结果。 但这可以正常工作,如果您只需要最大ID。
SELECT id
FROM table
WHERE id=(
SELECT max(price) FROM table
)
注意 :如果max(id)的值不是唯一的,则返回多行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.