sql - How to assign value to columns from StartDate to EndDate when StartDate is a fixed date, e.g. Jan 2013 -
i have table this:
country project invcode invname site workload startdate enddate usa 1234 2020 jane box 101 20 2012-02-10 2013-04-15 usa 1234 2020 jane box 102 35 2013-02-10 2013-07-15 usa 2222 2140 james smith 101 5 2012-10-10 2013-12-05 usa 2222 2590 susan falco 410 12 2013-05-10 2015-12-20 usa 2250 2140 james smith 401 8 2013-04-01 2013-07-18
i added 4 columns table: startyear, startmonth startdate , endyear, endmonth enddate (hopefully in writing query)
startyear startmonth endyear endmonth 2012 2 2013 5 2013 2 2013 7 2012 10 2013 12 2013 5 2015 12 2013 4 2013 7
the desired output this. couldn't fit months should go max month-year enddate. in table have columns jan 2013 through dec 2015
country|project|invcode|invname|site|startdate|enddate|jan-13|feb-13|mar-13|apr-13|may-13|. usa|1234|2020|jane box |101|2012-02-10|2013-05-15| 20 20 20 20 0 usa|1234| 2020|jane box |102|2013-02-10|2013-07-15| 0 35 35 35 35 usa|2222|2140|james smith|101|2012-10-10|2013-12-05| 5 5 5 5 5 usa|2222| 2590|susan falco|410|2013-05-10|2015-12-20| 0 0 0 0 12 usa|2250|2140|james smith|401|2013-04-01|2013-07-18| 0 0 0 8 8
when startdate before jan 2013, start jan 2013 , assign same value, e.g., 20 each month through enddate, after enddate assign 0 through max enddate.
when startdate after jan 2013 assign 0 months before month startdate , starting month equal month in startdate assign same value each month through enddate, e.g., startdate feb-2013, enddate jul-2013, workload=35, jan-2013 value of 0 assigned, feb-2013 through jul-2015 value of 35 assigned. after end date assign 0 through max end date.
i'll appreciate help!
here's start; you'll need fill out columns remaining months:
-- mysql select country, project, invcode, invname, site, startdate, enddate, case when 201301 between date_format(startdate, '%y%m') , date_format(enddate, '%y%m') workload else 0 end 'jan-13', case when 201302 between date_format(startdate, '%y%m') , date_format(enddate, '%y%m') workload else 0 end 'feb-13', ... , on through december my_table order whatever
addendum answered present tag (mysql), later noticed title said "sql server 2008" (which has since been moved tags).
the date "chopping" above different in sql server 2008, rest should same. because mysql , sql server both support year
, month
functions, following query, though makes each case
longer original mysql-only flavor, should work on either database:
-- sql server , mysql select country, project, invcode, invname, site, startdate, enddate, case when 201301 between year(startdate)*100 + month(startdate) , year(enddate)*100 + month(enddate) workload else 0 end 'jan-13', case when 201302 between year(startdate)*100 + month(startdate) , year(enddate)*100 + month(enddate) workload else 0 end 'feb-13', ... , on through december my_table order whatever
Comments
Post a Comment