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 |
我需要价格最高的id和批次
答案 0 :(得分:2)
获得每组最高记录的另一种方法
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
来挑选最新的ID
答案 1 :(得分:1)
您可以对按代码
分组的最大值使用连接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
答案 2 :(得分:0)
按价格排序,然后将结果限制为1:)
SELECT id, batch
FROM table_name
ORDER BY price DESC
LIMIT 1
答案 3 :(得分:0)
按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
强> 答案 4 :(得分:0)
select id,batch from table_name order by price desc limit 0,1
答案 5 :(得分:0)
试试这个:
SELECT `id`,`code`,`batch`, `price`
FROM `table_name`
WHERE `qty` > 0
GROUP BY `code` HAVING `price` = max(`price`)
答案 6 :(得分:-1)
price
)AS价格,id
,batch
FROM table_name
答案 7 :(得分:-1)
我不明白你需要单个结果或多个结果。但如果你只需要最大id,这个工作正常。
SELECT id
FROM table
WHERE id=(
SELECT max(price) FROM table
)
注意:如果max(id)的值不唯一,则返回多行。