Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join same table columns

I am working with android SQLite, and trying to combine same table data

My table looks like:

a  b  c
-------
3  5  0
3  3  0
3  7  1
4  6  0
4  8  1

3  8  7
4  6  8

for each 'a' where 'c'=0 make sum of 'b' and where 'c'=1 make sum of 'b'.

I tried inner join and more joins but none of them gave me the right answer.

like image 245
shay levi Avatar asked Jul 24 '26 19:07

shay levi


1 Answers

You should be able to do this with a simple GROUP BY and a SUM, like this:

SELECT
    a
,   SUM(CASE c WHEN 0 THEN b ELSE 0 END) as sum_0
,   SUM(CASE c WHEN 1 THEN b ELSE 0 END) as sum_1
FROM myTable
GROUP BY a

Demo on sqlfiddle.

like image 170
Sergey Kalinichenko Avatar answered Jul 27 '26 09:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!