使用SQL脚本查找哪个客户购买了iPhone或HTC的问题

时间:2019-12-13 08:58:32

标签: sql sql-server

我需要找到哪个客户购买了电话。如果客户仅购买iPhone或购买iPhone和HTC,那么我仅需要iPhone的数据。但是,如果客户仅购买HTC,我将需要HTC的数据。

原始数据

enter image description here

预期的输出表

enter image description here

我的代码无法正常工作,我不确定如何使用where子句。您能指导我在哪里出错吗?

下面是我的代码:

select Cust_ID, Year, Month, Product from custTable where Item_ID = (
Case 
when Item_ID in ('iPhone','HTC') then 'iPhone'
else 'HTC'
End )

2 个答案:

答案 0 :(得分:0)

尝试一下:

select  v1.Cust_ID,
        v1.Year,
        v1.Month,
        substring(min(Product),4,1000)  as  Product
from    (
            select  Cust_ID,
                    Year,
                    Month,
                    case when Product in ('iPhone') then '1. iPhone'
                        when Product in ('HTC') then '2. HTC'
                        else Product
                    end as  Product
            from    custTable
        ) v1
group by v1.Cust_ID,
        v1.Year,
        v1.Month

或者这个:

select  v1.Cust_ID,
        v1.Year,
        v1.Month,
        v1.Product
from    (
            select  Cust_ID,
                    Year,
                    Month,
                    Product,
                    ROW_NUMBER() over(partition by Cust_ID, Year, Month order by case when Product = 'iPhone' then 1 when Product = 'HTC' then 2 else 999 end)  as  rn
            from    custTable
        ) v1
where   v1.rn = 1

答案 1 :(得分:0)

您可以使用not exists

select o.*
from original o
where o.product = 'iPhone' or
      (o.product = 'HTC' and
       not exists (select 1
                   from original o2
                   where o2.cust_id = o.cust_id and
                         o2.product = 'iPhone'
                  )
      );

这几乎是您条件的直接翻译。