簡體   English   中英

獲取ID在MySQL中價格最大的地方

[英]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價格, idbatch 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM