SQL- WHERE and HAVING

170 views Asked by At

our task is to replace GROUP BY and HAVING clauses with WHERE, if possible. SQL-Code is as follows:

SELECT Sparte , Region , SUM( Umsatz )
FROM Fakten
GROUP BY Sparte , Region
HAVING SUM( Umsatz ) >= 50000

Is it possible to change the last two lines using WHERE? If not, why? Thank you in anticipation.

2

There are 2 answers

0
Matteo Tassinari On BEST ANSWER

If you really need to use WHERE instead of HAVING

SELECT * FROM (
  SELECT Sparte , Region , SUM(Umsatz) as S_Umsatz
  FROM Fakten
  GROUP BY Sparte , Region
) d
WHERE S_Umsatz >= 50000
1
Eduardo Molteni On

WHERE will filter based on the actual rows
HAVING will filter after the GROUP BY kicks in

Both have different use cases

Edit If you want to use a subquery you can do

SELECT Sparte, Region , SUM( Umsatz )
FROM Fakten
WHERE (SELECT SUM( Umsatz ) 
    FROM Fakten as F2 
    WHERE F2.Sparte = Fakten.Sparte
    AND F2.Region = Fakten.Region ) >= 50000
GROUP BY Sparte, Region

Or the Matteo way (Much more efficient and elegant)