Sql server 如果同一客户有不同的产品,如何放置单个标志

Sql server 如果同一客户有不同的产品,如何放置单个标志,sql-server,Sql Server,让我解释一下我的要求是什么。我需要检查是否有具有不同productid的客户如果是,那么我必须检查他们是否有任何producttype为null,如果任何customerid具有null producttype,那么这两个customerid的标志都应为N或Y 例如:我有一个表,其中有许多列。桌子结构 Customerid productid producttype 1 a x 1 b

让我解释一下我的要求是什么。我需要检查是否有具有不同productid的客户如果是,那么我必须检查他们是否有任何producttype为null,如果任何customerid具有null producttype,那么这两个customerid的标志都应为N或Y

例如:我有一个表,其中有许多列。桌子结构

Customerid   productid  producttype 

  1             a             x
  1             b            Null
  2             c             y
  2             d             y
  3             e             z
  3             f            Null
我想要的是如下所示:

Customerid  Productid   Productype  flag

1             a           x           N
1             b          Null         N
2             c           y           Y                       
2             d           y           Y
3             e           z           N
3             f          Null         N
到现在为止我都做了些什么

;with cte as
(

select * from test where customerid  in 

(select  customerid  from test  group by customerid having count(*) >1

) )
从这里,我收集了所有具有多个productid和不同ProductPE的customerid,现在我想添加标志部分

请让我知道这种方法是否好,以及我如何实现下一步


提前谢谢

你走在正确的轨道上。我曾使用过CTE,但内部查询不太复杂。 试试这个:

Create table #temp(Customerid int,   productid varchar(1), producttype varchar(1))
insert into #temp values
  (1,'a','x'),   
  (1,'b',Null),
  (2,'c','y'),   
  (2,'d','y'),   
  (3,'e','z'),   
  (3,'f',Null)


;with cte as
(
select distinct customerid, 'T' as tempflag from #temp where  producttype is null 
)
Select b.*,
case  a.tempflag when 'T' then 'N' else 'Y' end as Flag
 from cte a
right join #temp b
on a.customerid = b.customerid
输出:

Customerid  productid producttype Flag
----------- --------- ----------- ----
1           a         x           N
1           b         NULL        N
2           c         y           Y
2           d         y           Y
3           e         z           N
3           f         NULL        N