Hi all!
Today we have to do a clever sum using SQL statements.
We have to sum the number of elements in a table that match four different criteria and we want to aggregate them by year and month of reference. We also want to pick only the elements referring to the last 12 months.
Let us assume our table is in the form:
We want our result to count the elements with A=foo and b=boo, A=foo and B=bar, A=xxx and B=yyy and aggregate them by date. So our result will be:
2015, 12, 2
2016, 3,1
2016, 8, 1
The query is:
If you have any question feel free to ask in the comments! :)
Today we have to do a clever sum using SQL statements.
We have to sum the number of elements in a table that match four different criteria and we want to aggregate them by year and month of reference. We also want to pick only the elements referring to the last 12 months.
Let us assume our table is in the form:
ID | YEAR | MONTH | A | B |
---|---|---|---|---|
1234 | 2016 | 8 | foo | bar |
5678 | 2016 | 3 | boo | bar |
3412 | 2015 | 12 | foo | boo |
8888 | 2015 | 12 | foo | bar |
3412 | 2016 | 3 | xxx | yyy |
We want our result to count the elements with A=foo and b=boo, A=foo and B=bar, A=xxx and B=yyy and aggregate them by date. So our result will be:
2015, 12, 2
2016, 3,1
2016, 8, 1
The query is:
select yy, mm, SUM(qty) from ( select year(DATA) as yy, month(DATA) as mm ,count(*) as qty from table where (DATA)>= '2015-07-01 00:00:00.000' and (DATA)<= '2016-08-01 00:00:00.000' and A='foo' and B = 'boo' group by year(DATA),month(DATA) union all select year(DATA) as yy, month(DATA) as mm ,count(*) as qty from table where (DATA)>= '2015-07-01 00:00:00.000' and (DATA)<= '2016-08-01 00:00:00.000' and A='foo' and B = 'bar' group by year(DATA),month(DATA)
union all
select year(DATA) as yy, month(DATA) as mm ,count(*) as qty
from table
where (DATA)>= '2015-07-01 00:00:00.000' and
(DATA)<= '2016-08-01 00:00:00.000' and
A='xxx' and B = 'yyy'
group by year(DATA),month(DATA)
)t group by year, month
order by year, month
The query actually is quite simple yet not so easy to combine. We do three different queries for the three views that we want to sum up, we use the union all statement to put them toghether in the same result set, then we use the outer query to perform the sum. This query has been tested over SQL Server, but it should work fine with any RDBMS. Notice the t is not a typo but an alias for the subquery!
If you have any question feel free to ask in the comments! :)
Commenti
Posta un commento