|
scottichrosaviakosmos
Yak Posting Veteran
66 Posts |
Posted - 2010-10-15 : 23:56:16
|
| declare @tblmonth table(stdid int, code char(1), jan int, feb int, march int, april int, may int)declare @tbldate table(stdid int, sdate date, eddate date)insert into @tblmonthvalues (100, 'A', 10, 12, 50, 21, 30),(100, 'B', 12, 11, 9, 6, 45),(101, 'A', 12, 65, 45, 34, 23),(101, 'B', 34, 32, 12, 56, 34)insert into @tbldatevalues(100, '20100102', '20100505'),(101, '20100203', '20100302') select * from @tblmonthselect * from @tbldate;with cte as( -- Unpivot @tblmonth select t.stdid, t.code, m.monthno, m.value from @tblmonth t cross apply ( values (1, jan), (2, feb), (3, march), (4, april), (5, may) ) m(monthno, value))select d.stdid, d.eddate, coalesce(sum(case when c.code = 'A' then c.value end), 0) A, coalesce(sum(case when c.code = 'B' then c.value end), 0) Bfrom @tbldate dleft join declare @tblmonth table(stdid int, code char(1), jan int, feb int, march int, april int, may int)declare @tbldate table(stdid int, sdate date, eddate date)insert into @tblmonthvalues (100, 'A', 10, 12, 50, 21, 30),(100, 'B', 12, 11, 9, 6, 45),(101, 'A', 12, 65, 45, 34, 23),(101, 'B', 34, 32, 12, 56, 34)insert into @tbldatevalues(100, '20100102', '20100505'),(101, '20100203', '20100302') select * from @tblmonthselect * from @tbldate;with cte as( -- Unpivot @tblmonth select t.stdid, t.code, m.monthno, m.value from @tblmonth t cross apply ( values (1, jan), (2, feb), (3, march), (4, april), (5, may) ) m(monthno, value))select d.stdid, d.eddate, coalesce(sum(case when c.code = 'A' then c.value end), 0) A, coalesce(sum(case when c.code = 'B' then c.value end), 0) Bfrom @tbldate dleft join cte c on c.stdid = d.stdid --and month(eddate) < monthnogroup by d.stdid, d.eddateorder by d.stdidgroup by d.stdid, d.eddateorder by d.stdid--------------Now i want to put a condition on my final result column of A and B that if edate is of month march then sum will be March+ april +may or if edate is of month april then April + may.Right now the column A and B in final result is direct sum of all columns of first table.How to get that.scoo |
|