【问题标题】:sql query to fetch records with equal to and not equal to conditionsql查询以获取等于和不等于条件的记录
【发布时间】:2021-12-17 00:11:41
【问题描述】:

我必须从客户表中获取记录,其中客户gift_type 仅为“现金”,但这些客户不应该签署“优惠券”和“折扣”。以下是我的查询,它没有提供确切的记录。超过 1 个 gift_type 也包括在内。我也试过用子查询,还是不行。

select cust_id from customer where gift_type='cash' and gift_type != 'coupon' and gift_type != 'discount';

&

select cust_id 
from customer c1, customer c2 
where c1.gift_type='cash' and c2.gift_type != 'coupon' and c2.gift_type != 'discount';

提前感谢您的帮助。

【问题讨论】:

  • 你用的是oracle还是mysql?
  • 我正在使用 oracle

标签: mysql sql oracle where-clause


【解决方案1】:
select c.*
 from customer as c
 where c.gift_type='cash'
 and not exists
(
   select 1 from customer as x
     where c.customer_id=x.customer_id
      and x.gift_type in('coupon','discount')
)

希望以上内容适合你

【讨论】:

    【解决方案2】:

    您可能希望使用not innot exists,因为您希望所有gift_type 为现金的客户,但同时这些相同客户不得存在于其他礼品类型的表中。

    选项 1

    select * from customer a
    where a.gift_type = 'cash' and 
    not exists 
    ( select 1 from customer c where a.customer_id = c.customer_id and c.gift_type in ('coupon' , 'discount' )
    );
    

    选项 2

    select * from customer a
    where a.gift_type = 'cash' and 
    a.customer_id not in 
    ( select c.customer_id from customer c where a.customer_id = c.customer_id and 
      c.gift_type in ('coupon' , 'discount' )
    );
    

    【讨论】:

    • 关键字段是customer_id
    • @HaameemShimar,针对 Oracle 和关键字段 customer_id 进行了更新
    【解决方案3】:

    您可以在单个表扫描中使用:

    SELECT *
    FROM   (
      SELECT c.*,
             COUNT(CASE WHEN gift_type IN ('coupon', 'discount') THEN 1 END)
               OVER (PARTITION BY customer_id) AS num_invalid
      FROM   customer c
    ) c
    WHERE  gift_type = 'cash'
    AND    num_invalid = 0;
    

    其中,对于样本数据:

    CREATE TABLE customer (customer_id INT, gift_type VARCHAR(10));
    
    INSERT INTO customer(customer_id, gift_type)
    SELECT 1, 'cash'     FROM DUAL UNION ALL
    SELECT 1, 'coupon'   FROM DUAL UNION ALL
    SELECT 2, 'cash'     FROM DUAL UNION ALL
    SELECT 2, 'discount' FROM DUAL UNION ALL
    SELECT 3, 'cash'     FROM DUAL;
    

    输出:

    CUSTOMER_ID GIFT_TYPE NUM_INVALID
    3 cash 0

    Oracle db<>fiddle MySQL db<>fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-16
      • 2013-10-30
      • 1970-01-01
      • 2020-05-29
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多