tsql - SQL Server SUM based on subsequent records -
microsoft sql server 2012 (sp1) - 11.0.3156.0 (x64)
i not sure of best way word , have tried few different searches different combinations of words without success.
i want sum sequence = 1 when there sequence > 1, in table below sequence = 1 lines marked *. don't care @ checking sequence 2,3,etc match same pattern because if exist @ need sum them.
i have data looks this:
| sequence | id | num | otherid | |----------|----|-----|---------| | 1 | 1 | 10 | 1 |* | 2 | 1 | 15 | 1 | | 3 | 1 | 20 | 1 | | 1 | 2 | 10 | 1 |* | 2 | 2 | 15 | 1 | | 1 | 3 | 10 | 1 | | 1 | 1 | 40 | 3 | i need sum num column when there more 1 sequence. output this:
sequence sum otherid 1 20 1 2 30 1 3 20 1 i have tried grouping queries in bunch of different ways time sum, don't know how look ahead make sure there greater 1 sequences id.
my query @ moment looks this:
select sequence, sum(num) [sum], otherid tbl id in (select id tbl sequence > 1) group sequence, otherid tbl cte wrapped around query , partially works, not filter wanted.
if shouldn't done or can't done can handle that, if it's missing i'd fix query.
edit:
i can't give full query here started table/data (to above output). otherid there because data has same id/sequence combinations otherid helps separate them out rows not identical (multiple questions on form).
create table #tmptable (id int, sequence int, num int, otherid int) insert #tmptable (id, sequence, num, otherid) values (1, 1, 10, 1) insert #tmptable (id, sequence, num, otherid) values (1, 2, 15, 1) insert #tmptable (id, sequence, num, otherid) values (1, 3, 20, 1) insert #tmptable (id, sequence, num, otherid) values (2, 1, 10, 1) insert #tmptable (id, sequence, num, otherid) values (2, 2, 15, 1) insert #tmptable (id, sequence, num, otherid) values (3, 1, 10, 1) insert #tmptable (id, sequence, num, otherid) values (1, 1, 40, 3)
the following sum on sequence , otherid, when: either
- sequence greater 1
or
- there else same id , otherid, different sequence.
query:
select sequence, sum(num) sumnum, otherid @tmptable sequence > 1 or exists (select * @tmptable b a.id = b.id , a.otherid = b.otherid , b.sequence <> a.sequence) group sequence, otherid;
Comments
Post a Comment