简体   繁体   中英

SQL where clause to work with Group by clause after performing a count()

Tried my usual references at w3schools and google. No luck

I'm trying to produce the following results. QTY is a derived column

   | Position | QTY
 --------------------
 1   Clerk      2
 2   Mgr        2   

Here's what I'm not having luck with:

  SELECT Position, Count(position) AS 'QTY'
    FROM tblemployee
   Where ('QTY' != 1)
GROUP BY Position

I know that my Position is set up as varchar(255) Count produces a integer data and my where clasue is accurate so that leads me to believe that that Count() is jamming me up. Please throw up an example so I can reference later. Thanks for the help!

SELECT Position, Count(position) AS 'QTY'
FROM tblemployee
GROUP BY Position
HAVING Count(Position) != 1

Note: this is how it will be in SQL Server & should also be the case with mysql (I guess).

That's what the HAVING clause is for:

SELECT Position, Count(position) AS 'QTY'
FROM tblemployee
GROUP BY Position
HAVING QTY != 1

In SQL Server, I'd do:

SELECT Position, Count(position) AS 'QTY' 
FROM tblemployee 
GROUP BY Position 
HAVING COUNT(position) <> 1

I don't know if that works in MySql, but I believe it is standard SQL syntax.

There's a couple of issues. In SQL you can't reference the QTY column by name (in this case). Also, since you're grouping and want to exclude a certain value you have to use the "HAVING" clause instead of the where clause.

The where clause CAN be used to twit out thins that you don't want to count. (see example 2)

ST

SELECT Position, Count(position) AS QTY
FROM tblemployee
GROUP BY Position
HAVING Count(position) <> 1

-- Example 2
-- Don't count poor old Johnny
SELECT Position, Count(position) AS QTY
FROM tblemployee
WHERE Position <> 'Johnny'
GROUP BY Position
HAVING Count(position) <> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM