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.
Author |
Topic |
sumo
Starting Member
45 Posts |
Posted - 2003-10-21 : 14:05:54
|
I have the following sample data:1995 VOLKSWAGEN GOLF1996 VOLKSWAGEN GOLF1999 VOLKSWAGEN GOLF2000 VOLKSWAGEN GOLF2001 VOLKSWAGEN GOLF2003 VOLKSWAGEN GOLF1995 HONDA CIVIC1996 HONDA CIVIC1999 HONDA CIVIC2000 HONDA CIVIC I am having trouble figuring out how to query this data to group it like the following:1995-1996 VOLKSWAGEN GOLF1999-2001 VOLKSWAGEN GOLF2003-2003 VOLKSWAGEN GOLF1995-1996 HONDA CIVIC1999-2000 HONDA CIVIC The idea is to group the data by adjacent years and display the range of years in the grouping. I can't see a way to do this without looping row-by-row on the data with a cursor or an outside program (i.e. VB). Anyone have any ideas?Michael SumeranoTechnical Web AdministratoreKeystone.comhttp://www.ekeystone.com/ |
|
Stoad
Freaky Yak Linguist
1983 Posts |
Posted - 2003-10-21 : 16:14:52
|
selectcast(min(Y) as char(4)) + ' - ' + cast(max(Y) as char(4)) as YearSpan,Carfrom(select Car, Y,Y-(select count(distinct Y) from t tt where tt.Car=t.Car and tt.Y<t.Y) yyfrom t) zgroup by Car, yySeems this is one of those very very rare cases when it is worthcomparing against a cursor solution's performance. |
 |
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2003-10-21 : 16:15:49
|
Create a table with the years you want to query and join to thatcreate table #a (period char(11), y int)insert #a select '1995-1996', 1995insert #a select '1995-1996', 1996insert #a select '1997-1998', 1997...from tbljoin #aon tbl.yr = #a.ygroup by #a.periodYou then just need to think about how to populate #a.or justselect convert(char(4),((yr+1)/2)+1) + ' - ' + convert(char(4),((yr+1)/2)+2)...from tblgroup by (yr+1)/2or something like that==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
|
|