I have a table with three columns: Name, Country, Price and I need a SQL
query that creates a fourth Boolean
column named Qualify. This column needs to be true if Price<100 and there is no other row with price<100 and the same country.
Example:
Name - Country- Price- Qualify
Daniel - ES - 98 - TRUE
John - PT - 45 - TRUE
Maria - UK - 102 - FALSE
Anna - PT - 31 - FALSE (because there is already a row with PT and Price<100)
Joseph - UK - 25 - TRUE
Miriam -DK - 105 - FALSE
All this is because I do not want to count volumes more than one time if the price is under 100 and the country is the same. Is this even possible? Thanks
Think exists
. In MySQL, you don't even need a case
expression:
select t.*,
(t.price < 100 and
not exists (select 1
from t t2
where t2.country = t.country and t2.name <> t.name and t2.price < 100
)
) as flag
from t;
This assumes that name
is unique, at least with respect to country.
Just providing another option using CASE statement:
Select
@row_number:=CASE
WHEN @country = Country AND Price < 100 AND @price < 100
THEN 1
ELSE 0 END AS Qualify,
@country:= Country As Country,
@price:= Price As Price
FROM
Test
ORDER BY Country, Price
Here is the demo
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.