Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL : Conditionally select column based on aggregate value

The answer to this question:

Display the total number of operators hired each year.

is this:

SELECT
    COUNT(YEAR(HireDate)) AS 'Count',
    YEAR(HireDate) AS 'Year'
FROM Operators
GROUP BY YEAR(HireDate);

But how would I modify that for this question:

Display the number of operators hired in each year where more than one operator was hired.

I tried to do

WHERE Count >= 1

or

WHERE COUNT(YEAR(HireDate)) > 1

but nothing worked. I did research CASE statements but I couldn't find anything suiting what I need to do, any idea?

Using SQL Server 2008

like image 546
Alde Avatar asked May 03 '26 15:05

Alde


1 Answers

Use Having clause

SELECT
    COUNT(YEAR(HireDate)) AS 'Count',
    YEAR(HireDate) AS 'Year'
FROM Operators
GROUP BY YEAR(HireDate)
HAVING Count >= 1;

Read More

like image 154
Ashraful Islam Avatar answered May 06 '26 08:05

Ashraful Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!