I am a little confused about WHERE and HAVING when it comes to SQLs like these below.
Most of the time when I create any SQL with aggregated column, like SUM, I start with:[pre]
SELECT FIELD_A, FIELD_B
FROM MY_TABLE
WHERE (FIELD_A = ...)
ORDER BY FIELD_A[/pre]
Then I ‘wrap’ my FIELD_B in a SUM and GROUP BY whatever column(s) I need, and I have this SQL:[pre]
SELECT FIELD_A, SUM(FIELD_B) AS MYSUM
FROM MY_TABLE[blue]
WHERE (FIELD_A = ...)[/blue]
GROUP BY FIELD_A
ORDER BY FIELD_A[/pre]
Or I can run this SQL:[pre]
SELECT FIELD_A, SUM(FIELD_B) AS MYSUM
FROM MY_TABLE
GROUP BY FIELD_A[blue]
HAVING (FIELD_A = ...)[/blue]
ORDER BY FIELD_A[/pre]
And the outcome is the same from both SQLs.
Is there any ‘preference’ of which one to use? Is last one more ‘correct’ than the other?
In examples I see mostly the last one as the way to go, but the first one gives me the same outcome, so in my opinion is also correct. Right?
I would appreciate any light on the issue here.
Have fun.
---- Andy
A bus station is where a bus stops. A train station is where a train stops. On my desk, I have a work station.
Most of the time when I create any SQL with aggregated column, like SUM, I start with:[pre]
SELECT FIELD_A, FIELD_B
FROM MY_TABLE
WHERE (FIELD_A = ...)
ORDER BY FIELD_A[/pre]
Then I ‘wrap’ my FIELD_B in a SUM and GROUP BY whatever column(s) I need, and I have this SQL:[pre]
SELECT FIELD_A, SUM(FIELD_B) AS MYSUM
FROM MY_TABLE[blue]
WHERE (FIELD_A = ...)[/blue]
GROUP BY FIELD_A
ORDER BY FIELD_A[/pre]
Or I can run this SQL:[pre]
SELECT FIELD_A, SUM(FIELD_B) AS MYSUM
FROM MY_TABLE
GROUP BY FIELD_A[blue]
HAVING (FIELD_A = ...)[/blue]
ORDER BY FIELD_A[/pre]
And the outcome is the same from both SQLs.
Is there any ‘preference’ of which one to use? Is last one more ‘correct’ than the other?
In examples I see mostly the last one as the way to go, but the first one gives me the same outcome, so in my opinion is also correct. Right?
I would appreciate any light on the issue here.
Have fun.
---- Andy
A bus station is where a bus stops. A train station is where a train stops. On my desk, I have a work station.