简体   繁体   English

SQL,如果条件为真,则仅计数一次

[英]SQL if condition true, count only once

I have a table with three columns: Name, Country, Price and I need a SQL query that creates a fourth Boolean column named Qualify. 我有一个包含三列的表:名称,国家/地区和价格,并且我需要一个SQL查询来创建名为Qualify的第四个Boolean列。 This column needs to be true if Price<100 and there is no other row with price<100 and the same country. 如果Price <100,且没有其他行的价格<100,且同一国家/地区,则此列必须为true。

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. 所有这一切是因为如果价格低于100并且所在国家/地区相同,我不想重复计算多次。 Is this even possible? 这有可能吗? Thanks 谢谢

Think exists . 思考exists In MySQL, you don't even need a case expression: 在MySQL中,您甚至不需要case表达式:

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. 假定name至少在国家/地区方面是唯一的。

Just providing another option using CASE statement: 只需使用CASE语句提供另一个选项:

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 这是演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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