Using WHERE with GROUP BY

You can also use the WHERE clause along with the GROUP BY clause. The GROUP BY clause will go after the WHERE clause like so:

USE lahmansbaseballdb;
SELECT playerid, teamid
FROM batting
WHERE playerid = 'aardsda01'
GROUP BY teamid, playerid;

The previous query returns the results shown in the following screenshot: 

Here, you can see that you are now only getting the results for aardsda01

As a comparison, if you execute the previous query without GROUP BY, the query will return one additional row: 

USE lahmansbaseballdb;
SELECT playerid, teamid
FROM batting
WHERE playerid = 'aardsda01';

The following screenshot shows the results of running the previous query: 

You can now see two rows containing style. This is because this player was on the Seattle team for 2 years, whereas he was only on the other teams for 1 year. You can view this information by executing the following query: 

USE lahmansbaseballdb
SELECT playerid, teamid, yearid
FROM batting
WHERE playerid = 'aardsda01';

The following screenshot shows you the results of running the previous query: 

Here, you can see that teamid is not unique because there are 2 years for the SEA team ID. This shows us that GROUP BY is like using DISTINCT.

The following table shows a comparison between GROUP BY and DISTINCT

GROUP BY query DISTINCT query

USE lahmansbaseballdb; 
SELECT playerid, teamid
FROM batting
WHERE playerid = 'aardsda01'
GROUP BY teamid, playerid;

USE lahmansbaseballdb; 
SELECT DISTINCT playerid, teamid
FROM lahmansbaseballdb.batting
WHERE playerid = 'aardsda01';

GROUP BY query results

DISTINCT query results 

 

Here, you can see that GROUP BY, without aggregate functions, produces the same results as DISTINCT

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.196.175