SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Select Count(*) Where T2.year > T1.year
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

m1k3ch3ck
Starting Member

7 Posts

Posted - 06/06/2012 :  08:48:09  Show Profile  Reply with Quote
hey guys,
i have been into sql for a while, but havent used it in maybe one or two years.
nevertheless i do not understand the following simple introduction example:

Edited by - m1k3ch3ck on 06/06/2012 08:50:05

nigelrivett
Flowing Fount of Yak Knowledge

United Kingdom
3328 Posts

Posted - 06/06/2012 :  09:01:24  Show Profile  Visit nigelrivett's Homepage  Reply with Quote
It's a correlated subquery. It runs for each row in t1

So - take a row in t1, that has a value for year.
count all the rows from t2 where year is less than that year, add 1 to it (in this case could be <= without the +).
The resultset is each year in t1 plus the above calculation for each of those rows.

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

m1k3ch3ck
Starting Member

7 Posts

Posted - 06/06/2012 :  11:14:55  Show Profile  Reply with Quote
k. got that.
already understood that its a subquery, and also that its correlated.

didnt (and kinda still dont) get the sence why someone would run a query like this, even though i do now understand the mechanic behind it and what it does.
Go to Top of Page

nigelrivett
Flowing Fount of Yak Knowledge

United Kingdom
3328 Posts

Posted - 06/06/2012 :  11:21:51  Show Profile  Visit nigelrivett's Homepage  Reply with Quote
It's quite common.
Find how many entries there are prior to the end of each year.
Probably more sensible to aggregate per year then sum the prior years but if there's not much data this is simpler.

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000