Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Select sum group by

Author  Topic 

calvinkwoo3000
Yak Posting Veteran

98 Posts

Posted - 2009-12-16 : 02:34:29
hi everyone,

i face a problem in grouping my table.

i had a table as below:

goodid year jan feb march ............
------------------------------------------
id1 2009 10 10 10
id1 2010 10 10 10
id2 2009 20 20 20
id2 2008 20 20 20

i wish the query result as below:
goodid year jan feb march ............
------------------------------------------
id1 2010 20 20 20
id2 2009 40 40 40

mean i need to sum(jan), sum(feb)...... group by goodid and i need the lastest year to be display too.

Can anyone can guide me on this??
Thanks...............





khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-12-16 : 03:19:53
if you are not using SQL 2005/2008

select t.goodid, t.year, jan = sum(jan), feb = sum(feb), . . .
from mytable t
inner join
(
select goodid, year = max(year)
from mytable
group by goodid
) m on t.goodid = m.goodid and t.year = m.year
group by goodid


and if you are using SQL 2005/2008

select *
from
(
select t.goodid, t.year, row_no = row_number() over(partition by t.goodid order by t.year desc),
jan = sum(jan), feb = sum(feb), . . .
from mytable t
group by goodid, t.year
) t
where t.row_no = 1




KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

calvinkwoo3000
Yak Posting Veteran

98 Posts

Posted - 2009-12-16 : 04:17:23
Hi khtan,

i very appreaciate your help. Thank you.
This is what i want.
quote:
Originally posted by khtan

if you are not using SQL 2005/2008

select t.goodid, t.year, jan = sum(jan), feb = sum(feb), . . .
from mytable t
inner join
(
select goodid, year = max(year)
from mytable
group by goodid
) m on t.goodid = m.goodid and t.year = m.year
group by goodid


and if you are using SQL 2005/2008

select *
from
(
select t.goodid, t.year, row_no = row_number() over(partition by t.goodid order by t.year desc),
jan = sum(jan), feb = sum(feb), . . .
from mytable t
group by goodid, t.year
) t
where t.row_no = 1




KH
[spoiler]Time is always against us[/spoiler]



Go to Top of Page
   

- Advertisement -