使用SQL脚本查找购买iphone或HTC的客户时遇到问题

使用SQL脚本查找购买iphone或HTC的客户时遇到问题,sql,sql-server,Sql,Sql Server,我需要找到哪个顾客买了手机。如果客户只购买iPhone或iPhone和HTC,那么我只需要iPhone的数据。但是如果客户只购买HTC,我需要HTC的数据 原始数据 预期输出表 我的代码不起作用,我不知道如何使用where子句。你能告诉我哪里出错了吗 下面是我的代码: select Cust_ID, Year, Month, Product from custTable where Item_ID = ( Case when Item_ID in ('iPhone','HTC') then

我需要找到哪个顾客买了手机。如果客户只购买iPhone或iPhone和HTC,那么我只需要iPhone的数据。但是如果客户只购买HTC,我需要HTC的数据

原始数据

预期输出表

我的代码不起作用,我不知道如何使用where子句。你能告诉我哪里出错了吗

下面是我的代码:

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

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

您可以使用
不存在

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'
                  )
      );
这几乎是你的条件的直接翻译