views:

24

answers:

1

How can I use the value from an outer clause inside an inner clause using nested SELECT statements? Eg:

SELECT cost AS c, quantity, (SELECT COUNT(1) FROM accounts WHERE cost = c) 
FROM accounts

Can c be referenced in the inner SELECT clause as attempted above?

+2  A: 

Alias the outer table (eg. FROM accounts AS a). Then you can simply do a.cost in the inner subquery.

EDIT. That being said, there's a better way to write this query without a sub-query for each row:

SELECT a.cost, a.quantity, COUNT(b.id) AS count
FROM accounts AS a LEFT JOIN accounts AS b ON b.cost = a.cost
reko_t
@reko: how does the inner clause know whether it is the outer or inner version of accounts?
Craig Johnston
ah, sorry, should alias the outer table as something else and use the alias. i'll edit the answer
reko_t
What SQL are you using? I can't seem to alias tables like that. I can only do: accounts a
Craig Johnston
Well, I'm mostly familiar with MySQL, but it's all the same; `accounts a` and `accounts AS a` does the same thing.
reko_t