简体   繁体   中英

Mysql query to select row based on column value

id date is_available product_id product_recalled
200 2019-10-10 1 123 yes
201 2020-07-10 1 123 no
202 2020-08-11 0 123 yes
203 2021-07-10 0 123 yes
204 2021-01-10 0 123 no
205 2021-07-10 0 124 yes
206 2021-01-10 0 124 no

I need a query to select the max row based on the is_available column value sorted by latest date. If is_available = 1 for the product, I should get the max row for with is_available = 0. Similarly, if a product only has is_available set to 0, I should get the max row for is_available = 0.

If a product id has both is_available =1 and is_available = 0, then I need to get the latest record with is_available = 1 which is the case for product id 123. For product id 124, there is no is_available = 1 so I need to get the latest record with is_available = 0.

Eg: Scenario 1: If I specify the product_id = 123, then the expected output should be

id date is_available product_id product_recalled
201 2020-07-10 1 123 no

Scenario 2: If I specify the product_id = 124, then the expected output should be

id date is_available product_id product_recalled
205 2021-07-10 0 124 yes

I am not sure how to write a single query that would do this. Any help would be appreciated.

WITH cte AS (
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY is_available DESC, date DESC) rn
  FROM test
)
SELECT *
FROM cte
WHERE rn = 1;

For to select the row for definite product use

SELECT *
FROM test
WHERE product_id = @product_id
ORDER BY is_available DESC, date DESC
LIMIT 1;

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM