join - How to make this SQL SELECT? -
i cant figure out how make comparison select both years every plant.
select plantname, sum(amount) amount_harvested_2014 harvest year=2014 group plantname
in desired output row should this:
plantname 2014amount 2015amount 2015-2014amount
the table:
create table harvest( harvest_id int primary key identity(1,1), plantname nvarchar(20) not null foreign key references plants(plantname), amount int not null, year int, harvester_id int not null foreign key references workers(worker_id) )
and example content of table:
harvest_id plantname amount year harvester_id 1 rose 32 2015 2 2 rose 12 2015 5
one simple way (which might not best) use conditional aggregation this:
select plantname ,sum(case when year=2014 amount else 0 end) "2014amount" ,sum(case when year=2015 amount else 0 end) "2015amount" ,sum(case when year=2015 amount else 0 end) - sum(case when year=2014 amount else 0 end) "2015-2014amount" harvest group plantname
Comments
Post a Comment