SQL 2008
Basically i have a dataset that looks like this:
AcctID AcctType AcctSubType Curr TransType Amount Sequence
1 CCY SET EUR Opening 1000 B
1 CCY SET EUR BUY -100 T
1 CCY SET EUR SEL 100 T
1 CCY SET EUR Closing 1000 B
2 CCY SET EUR Opening 2000 B
2 CCY SET EUR SEL 100 T
2 CCY SET EUR Closing 2100 B
3 CCY INC EUR Opening 1000 B
3 CCY INC EUR SEL 200 T
3 CCY INC EUR BUY -100 T
3 CCY INC EUR Closing 1100 B
4 CCY SET GBP Opening 2000 B
4 CCY SET GBP SEL 100 T
4 CCY SET GBP Closing 2100 B
What i want to do is return all from the dataset where there are more than one capital account per currency (so basically more than one distinct AcctID). A capital account is identified by AcctType = ‘CCY’ and AcctSubType = ‘SET’. Also i only want the balances, so where Sequence = ‘B’.
So for the above dataset what would be returned is the following:
AcctID AcctType AcctSubType Curr TransType Amount Sequence
1 CCY SET EUR Opening 1000 B
1 CCY SET EUR Closing 1000 B
2 CCY SET EUR Opening 2000 B
2 CCY SET EUR Closing 2100 B
I started off like this, but got confused how to include the distinct count of AcctID within a currency is greater than 1:
;;with test (AcctID, AcctType, AcctSubType, Curr, TransType, Amount, Sequence)
as
(
select 1, 'CCY', 'SET', 'EUR', 'Opening', 1000, 'B'
union all select 1, 'CCY', 'SET', 'EUR', 'BUY', -100, 'T'
union all select 1, 'CCY', 'SET', 'EUR', 'SEL', 100, 'T'
union all select 1, 'CCY', 'SET', 'EUR', 'Closing', 1000, 'B'
union all select 2, 'CCY', 'SET', 'EUR', 'Opening', 2000, 'B'
union all select 2, 'CCY', 'SET', 'EUR', 'SEL', 100, 'T'
union all select 2, 'CCY', 'SET', 'EUR', 'Closing', 2100, 'B'
union all select 3, 'CCY', 'INC', 'EUR', 'Opening', 1000, 'B'
union all select 3, 'CCY', 'INC', 'EUR', 'SEL', 200, 'T'
union all select 3, 'CCY', 'INC', 'EUR', 'BUY', -100, 'T'
union all select 3, 'CCY', 'INC', 'EUR', 'Closing', 1100, 'B'
union all select 4, 'CCY', 'SET', 'GBP', 'Opening', 2000, 'B'
union all select 4, 'CCY', 'SET', 'GBP', 'SEL', 100, 'T'
union all select 4, 'CCY', 'SET', 'GBP', 'Closing', 2100, 'B'
)
select *
from test t
where t.AcctType = 'CCY'
and t.AcctSubType = 'SET'
and t.Sequence = 'B'
and t.Curr in (select w.Curr
from test w
where w.AcctType = 'CCY'
and w.AcctSubType = 'SET'
and w.Sequence = 'B'
group by w.Curr
having COUNT(distinct w.AcctID) > 1)
Now this works for the dataset, although what concerned me is would this work if there was more than one currency with more than one capital account? Does the code i’ve created work for what i want to achieve.
Many Thanks
try this.
UPD. And yes, your updated code seems to be working,