I’m pretty new to SQL, and I’m trying to do something like this:
I have a tabled called Foo with two columns in it: FooId (the primary key) and BarId (a non-nullable foreign key that can have duplicate values in it).
I want to write a query that returns the BarIds that only appear once in Foo. I also want to write another query that returns the BarIds that appear more than once in Foo.
I started with something like this:
SELECT
BarId,
COUNT(BarId) AS "BarCount"
FROM [Database].[dbo].[Foo]
GROUP BY BarId
Which returns the number of occurrences of each BarId. But as soon as I try to add a WHERE clause, I get a syntax error:
SELECT
BarId,
COUNT(BarId) AS "BarCount"
FROM [Database].[dbo].[Foo]
GROUP BY BarId
WHERE "BarCount" > 1
I’m sure this is some silly mistake that I am making by not understanding SQL very well. What am I doing wrong?
When used with aggregates, you need to use a
HAVINGclause instead of aWHEREclause: