sql - How to sum the total of same group and same month? -


i have view in following format:

channel | themonth | thecount | ------------------------------- chaa    |        3 |        5 | ------------------------------- chaa    |        2 |        2 | ------------------------------- chaa    |        1 |        4 | ------------------------------- chab    |        2 |        1 | ------------------------------- 

i sum thecount having same month current month (assuming current month march) previous month, chaa (channel) of 3 (themonth) have thecount value of 7 (5+2). expected output shown this:

channel | themonth | thecount | ------------------------------- chaa    |        3 |        7 |  --> note: row has been updated. ------------------------------- chaa    |        2 |        2 |  --> retain value ------------------------------- chaa    |        1 |        4 |  --> retain value ------------------------------- chab    |        2 |        1 |  --> retain value ------------------------------- 

i have been using sql case fix solution, following code, failed:

select channel, themonth,  case when month(date('2012-03-31')) = themonth ,       month(date('2012-03-31')) - 1 = themonth          sum(thecount)  else sum(thecount) end thecount theview 

is there alternate solution beside using sql case? please not limit database technology general sql query.

if database supports analytic function lag (oracle, db2, postgresql, terradata, ?) , no months missing (i.e. thecount = 0 instead of missing row):

select channel, themonth,   case     when themonth = 3     thecount + lag(thecount) on (partition channel order themonth)     else thecount   end thecount theview 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -