Frage

I wonder is it possible to make such query. The problem is that I have a table where are some numbers for date. Lets say I have 3 columns: Date, Value, Good/Bad

I.e:

2014-03-03 100 Good
2014-03-03 15 Bad
2014-03-04 120 Good
2014-03-04 10 Bad

And I want to select and subtract Good-Bad:

2014-03-03 85
2014-03-04 110

Is it possible? I am thinking a lot and don't have an idea yet. It would be rather simple if I had Good and Bad values in seperate tables.

War es hilfreich?

Lösung

The trick is to join your table back to it self as shown below. myTable as A will read only the Good rows and myTable as B will read only the Bad rows. Those rows then get joined into a signle row based on date.

SQL Fiddle Demo

select 
a.date
,a.count as Good_count
,b.count as bad_count
,a.count-b.count as diff_count
from myTable as a
inner join myTable as b
on a.date = b.date and b.type = 'Bad'
where a.type = 'Good'

Output returned:

DATE                            GOOD_COUNT  BAD_COUNT   DIFF_COUNT
March, 03 2014 00:00:00+0000    100           15         85
March, 04 2014 00:00:00+0000    120           10         110

Another aproach would be to use Group by instead of the inner join:

select 
a.date
,sum(case when type = 'Good' then a.count else  0 end) as Good_count
,sum(case when type = 'Bad' then a.count else  0 end) as Bad_count
,sum(case when type = 'Good' then a.count else  0 end)  - 
    sum(case when type = 'Bad' then a.count else  0 end) as Diff_count
from myTable as a
group by a.date
order by a.date

Both approaches produce the same result.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top