views:

89

answers:

6

What I'm trying to do is this:

select Store.Id, (select COUNT(*) from StoreProduct
where StoreProduct.Store_id = Store.Id) as _count from Store where _count > 3

SQL Server says it's invalid because the column name '_count' is invalid. Why it's invalid if I'm declaring it?

A: 

Try using a name that begins with a letter instead of an underscore.

eidylon
Invalid column name 'acount'.
Ciwee
underscores are perfectly valid according to standard identifier rules.
David Lively
Interesting. Good to know... guess that is consistent with how you can start identifiers with underscore in VB too. I did not know this.
eidylon
A: 

Why don't you try this?

select Store_id as Id, COUNT(1) as acount
from StoreProduct
group by Store_id
having count(1) > 3
eKek0
select Store.Id, (select COUNT(*) from StoreProduct where StoreProduct.Store_id = Store.Id) as acount from Store having acount > 3also didn't work.. it says acount is not valid.
Ciwee
+2  A: 

It's invalid to the WHERE clause because of the order of evaluation in SQL. The WHERE clause is second in the list, so can only see items present in the FROM clause (which is evaluated first). This old article has a breakdown of the evaluation order. I'm sure there's a newer one out there.

CodeByMoonlight
+1 for the information
Ciwee
+4  A: 
select Id as StoreId, count(*) as ProductCount
from StoreProduct
group by Id
having count(*) > 3

Another way

select S.Id, count(SP.ProductId) as ProductCount
from Store S
left join StoreProduct SP on (SP.Store_id = S.Id)
group by S.Id
having COUNT(SP.ProductId) > 3

Which, assumes, the unique column in your StoreProduct table is named ProductId

Chris Lively
+1 This works. :)
Mark Byers
+1 Indeed it works.. but I'm still curious: Why my __count column isn't recognized even in the having clause? Or better.. why do you have to put the count(*) in the having instead of it's alias, ProductCount? I tried and it didn't work.
Ciwee
A: 

Why not try this:

select a.StoreId,count(*) as TotProducts
from Store a
join StoreProduct b on b.storeId=a.storeID
group by a.storeID
having count(*) > 3

It appears that is what you are trying to accomplish?

Sparky
+1  A: 

'as' is used to logically rename a field within a query. You can't use it to rename a table, which is what your subquery returns, even though we know by context that the table returned by the subquery will only contain a single row.

I hope this helps.

Bob Jarvis
+1 Yes it helps. Actually I was wondering why I can't use the alias even in the 'having' clause. Your explanation seems reasonable.
Ciwee