2017-07-04 66 views
1

讓我解釋我的要求是什麼。我需要檢查,如果我有客戶提供不同的productid如果是的話,我要檢查,如果他們有任何producttype空或不是的情況下,任何在客戶中有NULL producttype則標誌這兩個客戶ID應該是N別的Ÿ如何把單旗如果相同的客戶有不同的產品

例如:我有一張桌子,裏面有很多列。 PFB的表stucture

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 

)) 

從此我收集所有的人都有一個以上的客戶ID productid和不同的producttpe現在我想添加標誌部分。

請讓我知道如果這種方法是好的,我該如何實現下一件事。

在此先感謝!

回答

2

你在正確的軌道上。我已經使用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 
+1

感謝您的幫助工程:) – Amitesh

相關問題