我有一个包含一些记录的表格,如下面的快照
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 :(得分: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