sql - GROUP BY with summing null values to every group -


i want group values , sum them category value - or none. example, have following table:

+-------+----------+ | value | category | +-------+----------+ |    99 |        | |    42 |        | |    76 |   [null] | |    66 |        b | |    10 |        c | |    13 |   [null] | |    27 |        c | +-------+----------+ 

my desired result should this:

+-------+----------+ |   sum | category | +-------+----------+ |   230 |        | |   155 |        b | |   126 |        c | |    89 |   [null] | +-------+----------+ 

i tried group category doesn't bring right numbers.

any ideas?

i'm using sql server 2012.

edit: ok, requested, can explain intents , give query far, although not helpful think.

i need sum value given categories , add sum of values without category [=> null] in example, sum

99 + 42 + 76 + 13 = 230 category 66 + 76 + 13 = 155      category b 10 + 27 + 76 + 13 = 126 category c 76 + 13 = 89            no category 

i hope gives idea of goal.

query far:

select sum([value]), [category] [mytable] group [category] 

first calculate sum of nulls add each group:

declare @t table     (       value int ,       category char(1)     )  insert  @t values  ( 99, 'a' ),         ( 42, 'a' ),         ( 76, null ),         ( 66, 'b' ),         ( 10, 'c' ),         ( 13, null ),         ( 27, 'c' )  ;with cte as(select sum(value) s @t category null) select category, sum(value) + s  @t cross join cte category not null group category, s 

another version:

;with cte as(select category, sum(value) over(partition category) +                   sum(case when category null value else 0 end) over() value               @t) select distinct * cte category not null 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -