Professional Documents
Culture Documents
UnitIntroduction
3 To TSQL
Unit 3
Modern Business
Technology
Developed by
Michael Hotek
Unit 3
Goals
• Nulls
• Group by
• Order by
• Distinct
• Aggregates
• Aggregates with grouping
• Having
• Compute
• Unions
Null
• WAIT A MINUTE!!!
Nulls cont.
(2 row(s) affected)
The Basics recap
• To quickly recap
or
exec sp_helpsort
Order by
(27 row(s) affected)
Order by / Nulls
(25 row(s) affected)
select distinct au_id from titleauthor
au_id
172321176
213468915
238957766
267412394
...
899462035
998723567
(19 row(s) affected)
Aggregates
(1 row(s) affected)
(1 row(s) affected)
Sum
(1 row(s) affected)
Avg
(1 row(s) affected)
(1 row(s) affected)
Group by
(7 row(s) affected)
(7 row(s) affected)
Group by and Nulls
(7 row(s) affected)
Group by and where
(5 row(s) affected)
Group by
(7 row(s) affected)
Group by
(3 row(s) affected)
avg
==========================
14.17
(6 row(s) affected)
Compute by
• A compute by is used to
subsummaries
• This construct must be used with an
order by
select title_id, type, price from titles where type
like '%cook%' order by type compute
avg(price) by type
title_id type price
MC2222 mod_cook 19.99
MC3021 mod_cook 2.99
avg
==========================
11.49
title_id type price
TC3218 trad_cook 20.95
TC4203 trad_cook 11.95
TC7777 trad_cook 14.99
avg
==========================
15.96
(7 row(s) affected)
Compute/Compute by
sum
==========================
22.98
title_id type price
MC2222 mod_cook 19.99
MC3021 mod_cook 2.99
sum
==========================
22.98
sum
==========================
45.96
(7 row(s) affected)
Compute/Compute by
Restrictions
• With a compute/computed by, you
can only use columns in the select
list
Restrictions
• Columns listed after the compute by
must be in the identical order to or a
subset of those listed after the order
by
Legal
• order by a,b,c
• compute by a,b,c
• compute by a,b
• compute avg(price) by a
Illegal
• order by a,b,c
• compute by b,a,c
• compute by c,a
• compute avg(price) by b
Unions
select * from authors where state = 'CA' union select * from authors where state
= 'MA'
au_lname state
Bennet CA
Carson CA
Dull CA
Green CA
Gringlesby CA
Hunter CA
Karsen CA
Locksley CA
MacFeather CA
McBadden CA
O'Leary CA
Straight CA
Stringer CA
White CA
Yokomoto CA
Burns MA
Johnson MA
Smithe MA
Smythe MA
(19 row(s) affected)
Unions