2015-04-02 82 views
1

具有計數的Sql我有像下面的一些記錄的表扣與相關價值

s.no cust_id  Balance id amount 
1  101   1   100 
2  102   1   200 
3  101   100   120 
4  102   100   50 
5  103   1   125 

我想要得到的記錄,如果平衡ID計數> 1。所以我需要這樣的確切輸出。

s.no cust_id  count  Balance 1 Balance 100 
1  101   2   100   120 
2  102   2   200   50 

回答

0

嘗試下面的查詢

declare @tb table(s_no int, cust_id int, Balance_id int, amount int) 
insert into @tb(s_no,cust_id,Balance_id, amount)values 
      (1,101,1,100), 
      (2,102,1,200), 
      (3 ,101,100,120), 
      (4,102,100,50), 
      (5,103,1,125) 

;with cte as 
(select cust_id,case when balance_id =1 then amount else 0 end as bls1,case when balance_id =100 then amount else 0 end as bls100 from @tb) 
select Row_number() over (order by cust_id) as srno,cust_id,count(*) as count,max(bls1) as [Balance 1],max(bls100) as [Balance 100] from cte group by cust_id having count(*)>1 
+0

太感謝你了.. – 2015-04-06 11:53:43