Você está na página 1de 1

78 Chapter 3: Selecting

Step 9: The ORDER BY clause is applied to sort the groups. The order within a
group doesnt matter because only one row is going to survive; its just the rela-
tive order of the groups that is determined at this point.
In all the previous steps the groups and rows have been shown in sorted
order for convenience, but its important to note that the actual ordering does
not occur until this point. And thats why certain features like FIRST and
NUMBER(*) havent been evaluated yet, because they depend on row ordering.

Note: ORDER BY places NULL values ahead of non-NULL values when ASC
(the default) is used.

Step 10: Each row is reduced to only the select list items, and each group is
reduced to a single row. This step is performed after the ORDER BY because
virtual columns can appear in the ORDER BY clause, so they have to survive
until this point.
Heres what the five groups look like after being reduced to five rows; the
original row labels are shown on the left so you can see which groups the final
rows came from:
a b c d
==== ==== = ====
R1 NULL NULL 8 2664
R2 100 NULL 2 666
R3 200 NULL 6 1998
E/F/G 200 3000 3 999
H/I/J 200 4000 3 999

Note: This step-by-step explanation assumes that select list items are evalu-
ated as soon as they can be. For example, at this point it is possible for a select
list expression involving a call to GROUPING to have been evaluated because
Step 7 took care of GROUPING calls. However, a select list expression involving
NUMBER(*) still cant be calculated, not until Step 13 at least.

Step 11: The summarizer (DISTINCT versus ALL) is applied to eliminate


duplicate rows; only DISTINCT has any effect. In this example, DISTINCT has
no effect because this particular GROUP BY clause guarantees that each row
will be distinct in the final result.
It is possible, however, for duplicate rows to remain after a GROUP BY
clause has been processed; this can happen if one or more columns named in the
GROUP BY clause are omitted from the select list. In that case the DISTINCT
summarizer would remove those remaining duplicate rows.
Step 12: The row range (FIRST, TOP, etc.) is applied to eliminate rows.
At this point the SELECT has reached its final form, at least as far as this
example is concerned:
SELECT DISTINCT
TOP 4 START AT 2
t1.key_1 * 100 AS a,
t3.key_1 * 1000 AS b,
COUNT(*) AS c,
SUM ( t3.non_key_1 ) AS d
FROM ( t1 LEFT OUTER JOIN t2 ON t1.key_1 = t2.key_1 )
CROSS JOIN t3

Você também pode gostar