0

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?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243

6 Answers6

4
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

NotMe
  • 87,343
  • 27
  • 171
  • 245
  • +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. – Andre Pena Jan 15 '10 at 00:24
3

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.

MartW
  • 12,348
  • 3
  • 44
  • 68
1

'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.

  • +1 Yes it helps. Actually I was wondering why I can't use the alias even in the 'having' clause. Your explanation seems reasonable. – Andre Pena Jan 15 '10 at 00:31
0

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

eidylon
  • 7,068
  • 20
  • 75
  • 118
0

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
  • 23,005
  • 25
  • 91
  • 119
  • select Store.Id, (select COUNT(*) from StoreProduct where StoreProduct.Store_id = Store.Id) as acount from Store having acount > 3 also didn't work.. it says acount is not valid. – Andre Pena Jan 15 '10 at 00:07
0

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
  • 14,967
  • 2
  • 31
  • 45