Link to home
Start Free TrialLog in
Avatar of michaelrobertfrench
michaelrobertfrench

asked on

t-sql - how to without a cursor implementation

Here is a very straightford sql to get me counts from the group by clause:

select
count(*) col1
from
tsys..tbl_base
group
by
base_month,
base_year

It returns:

col1
238875
239221
239454
239702
239965
240292
240708
241174
241624
241999
242426


Now without using a cursor I want to add a column to the result set to show the change in count.
Can you show me the sql that might accomplish this?
Avatar of BryanMI
BryanMI
Flag of United States of America image

Perhaps I'm not understanding the question...  much like what you did, I built this sample.  Can you tell me what else you're needing to return?
CREATE TABLE #Test (Month int, Year int, data varchar(10))
 
SET NOCOUNT ON
 
INSERT #Test (Month, Year, data) VALUES (12, 2008, 'test1')
INSERT #Test (Month, Year, data) VALUES (12, 2008, 'test2')
INSERT #Test (Month, Year, data) VALUES (12, 2008, 'test3')
 
INSERT #Test (Month, Year, data) VALUES (11, 2007, 'test4')
INSERT #Test (Month, Year, data) VALUES (11, 2007, 'test5')
INSERT #Test (Month, Year, data) VALUES (11, 2007, 'test6')
INSERT #Test (Month, Year, data) VALUES (11, 2007, 'test7')
 
INSERT #Test (Month, Year, data) VALUES (10, 2007, 'test8')
INSERT #Test (Month, Year, data) VALUES (10, 2007, 'test9')
 
SET NOCOUNT OFF
 
--RETURNS RECORD COUNT BY YEAR
SELECT Count(*) As RecordTotal, Year FROM #Test GROUP BY Year
 
--RETURNS RECORD COUNT BY MONTH AND YEAR
SELECT Count(*) As RecordTotal, Year, Month FROM #Test GROUP BY Year, Month
 
DROP TABLE #Test

Open in new window

Avatar of Guy Hengel [angelIII / a3]
what version of sql server are you using?
Avatar of michaelrobertfrench
michaelrobertfrench

ASKER

sql 2000
The result set would look like this:

col1      change_from_prior period
238875      
239221      346
239454      233
239702      248
239965      263
240292      327
240708      416
241174      466
241624      450
241999      375
242426      427

The change_from_prior_period is what I need the sql to provide.  An easy implementation with a cursor or a while loop but I want sql returning this result set.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes - Thank You Very Much