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 Count(*) Where T2.year > T1.year

Author  Topic 

m1k3ch3ck
Starting Member

7 Posts

Posted - 2012-06-06 : 08:48:09
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:

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-06 : 09:01:24
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 - 2012-06-06 : 11:14:55
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
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-06 : 11:21:51
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
   

- Advertisement -