Grouped Queries Flashcards
What is a grouped query
A query that contains
1. An aggregate function
2. A group by clause
3. Both
SQL Server 70-461 05-01
How many rows are returned per group?
1
SQL Server 70-461 05-01
What is the difference between WHERE and HAVING
- WHERE is evaluated at the row level
- HAVING is evaluated at the group level
SQL Server 70-461 05-01
Does WHERE or HAVING come first in logical query processing?
- WHERE is before HAVING in logical query processing
SQL Server 70-461 05-01
What aggregate functions does T-SQL support?
- Count(*)
- Count(FieldName)
- SUM
- AVG
- MIN
- MAX
SQL Server 70-461 05-01
How are nulls handled by aggregate functions?
- For all except Count(*), they are ignored
SQL Server 70-461 05-01
What is the difference between count(*) and count(FieldName)
- count(*) includes nulls
- count(FieldName) DOES NOT include nulls
SQL Server 70-461 05-01
Where is DISTINCT placed when using it in an aggregate function
SELECT shipperid, count(DISTINCT FieldName) AS numshippingdates FROM sales.orders GROUP BY shipperid
SQL Server 70-461 05-01
What aggregate function is DISTINCT most commonly used with
count
- example: count(DISTINCT shippeddate)
SQL Server 70-461 05-01
Why would you use a grouping set clause
- To write one succinct statement instead of, for example, four separate GROUP BY queries combined using UNION ALL
SQL Server 70-461 05-01
Example grouping set clause
GROUP BY GROUPINGSETS ( (shipperid, year(shippeddate)), (shipperid ), (year(shippeddate) ), ( ), );
Note: the blank parens represent an empty set
SQL Server 70-461 05-01
What is the output of a query with multiple grouping sets
- The output would be the same as if you had made a single query for each grouping set and then used UNION ALL to combine them.
SQL Server 70-461 05-01
Your three columns are shipperid, shipyear, numorders. In a GROUP BY GROUPINGSETS clause, what happens if the set doesn’t use all of the columns? For example, where shipper is is by itself in parens and shipyear is by itself in parens.
GROUP BY GROUPINGSETS ( (shipperid, shipyear), (shipperid ), (shipyear ), ( ), );
- The grouping set (shipperid ) doesn’t include shipyear so shipyear will be null in the results for this set.
- The grouping set (shipyear ) doesn’t include shipperid so shipperid will be null in the results for this set.
Note: count (*) AS numorders is always returned
SQL Server 70-461 05-01
What are the three clauses that allow multiple groupings in one query and where are they placed?
- GROUPINGSETS
- CUBE
- ROLLUP
Place these right after GROUP BY
SQL Server 70-461 05-01
What is the general form of the GROUP BY CUBE expression and how is it similar to GROUP BY GROUPING SETS?
GROUP BY CUBE(col1, col2, col3, etc)
GROUP BY CUBE(shipperid, year(shippeddate)
-Is the same as-
GROUP BY GROUPINGSETS
(
(shipperid, year(shippeddate)),
(shipperid ),
(year(shippeddate) ),
( ),
);
SQL Server 70-461 05-01