You need to understand how to use certain SQL clauses and operators to arrange SQL data so that it can be analyzed efficiently. Here are some suggestions on how to build statements to get the results you want.
Arranging data in a meaningful way can be a challenge. Sometimes you just need a simple classification. Often you have to do more processing - grouping for analysis and totaling. Fortunately, SQL provides a large number of clauses and operators for classification, grouping, and totaling. The suggestions below will help you know when to categorize, when to group, and when and how to total. For detailed information on each clause and operator, check out the online book.
#1: Categorical Sorting
Often, we do need to sort all the data. SQL's ORDER BY clause sorts data in alphabetical or numerical order. Therefore, homogeneous data are clearly classified into groups. However, these groups are just the result of classification, they are not real groups. ORDER BY displays each record, and a group may represent multiple records.
#2: Reduce similar data in groups
The biggest difference between classification and grouping is that classification data shows all records (within any limiting criteria), while grouped data does not show these records. The GROUP BY clause reduces similar data in a record. For example, GROUP BY can return a list of unique zip codes from a source file that duplicates those values:
SELECT ZIP
FROM Customers
GROUP BY ZIP
Include only those in the GROUP BY and SELECT column lists Chinese word meaning group column. In other words, the SELECT list must match the GROUP list. There is only one exception: the SELECT list can contain aggregate functions. (GROUP BY does not support aggregate functions.)
Remember that GROUP BY does not classify the resulting groups. To sort the group alphabetically or numerically, add an ORDER BY clause (#1). Additionally, you cannot reference an aliased domain in a GROUP BY clause. The group columns must be in the underlying data, but they do not have to appear in the results.
#3: Qualify data before grouping
You can add a WHERE clause to qualify the data grouped by GROUP BY. For example, the following statement only returns a list of zip codes for customers in the Kentucky area.
SELECT ZIP
FROM Customers
WHERE State = 'KY'
GROUP BY ZIP
WHERE filters the data before the GROUP BY clause obtains the value of the data. It is important to remember this important.
Like GROUP BY, WHERE does not support aggregate functions.
#4: Return all groups
When you filter data with WHERE, the resulting groups show only those records you specify. Data that matches the group definition but does not satisfy the clause conditions will not appear in the group. Regardless of the WHERE condition, if you want to include all data, add an ALL clause. For example, adding an ALL clause to the previous statement would return all zip code groups, not just those in Kentucky.
SELECT ZIP