Você está na página 1de 88

TERADATA

Advanced SQL

Change mode from BTET to ANSI


.SET Session Transaction ANSI

Change mode from ANSI to BTET


.SET Session Transaction BTET

Display error if Command other than TD Standard


.set session SQLFLAG ENTRY
.set session SQLFLAG NONE

Window Aggregate Functions


A window specification is applied is called a window
aggregate function. Window aggregate functions are
used to perform OLAP, which permits analysis of data
in the data warehouse or data mart.
Count Window - Generation of total counts and subcounts.
Sum Window - Generation of totals and subtotals.
Cumulative Sum -- Permits cumulative summation of
a value over time or any dimension.
Moving Average -- Permits computation of a moving
average based on a specified window.
Moving Sum -- Permits calculation of a moving sum
over time based on a specified window.
Moving
Difference
-- Permits
calculation
of afunctions
moving
Like
traditional
aggregate functions,
window
aggregate
operate
on groups
rows based
and permit
filtering of the
difference
overoftime
on qualification
a specifiedand
window.
group result. Unlike aggregations, OLAP functions return individual

Window aggregate functions produce


OLAP results:
Sub-counts
Final counts
Sub-totals
Final totals
Cumulative Sums
Moving Sums
Moving Averages
Moving
Differences
Window
functions
may be performed on:
# Tables ( Perm, Temp, Derived )
# Views
# INSERT/SELECT populations

The COUNT Window function may be used to perform the following


operations:
Count the number of rows in a defined group or in all groups
A similar result can be produced using the WITH and WITH...BY
extensions to
Teradata SQL. The WITH...BY function is used to produce sub-totals
(and
sub-counts) over the detail data for a group, as defined by the BY
clause.
Similarly, the WITH function is used to provide grand totals (and
grand counts)
over the detail data for all rows.
The COUNT Window function is an ANSI-standard function, whereas
the
WITH and WITH...BY functions are TD standard.
The COUNT Window function also produces true relational output
(uniform columns and rows) whereas WITH and WITH...BY do not.

SELECT
ename, sal, deptno
,COUNT(deptno) OVER ( ) AS
Total_Count
FROM samples.emp WHERE Deptno IN
(10,30)
ORDER BY 3,1;

SELECT
ename, sal, deptno
FROM samples.emp WHERE Deptno IN
(10,30)
WITH COUNT (Deptno) (TITLE 'Total_Count')
ORDER BY 3,1;

SELECT
ename, sal, deptno
,COUNT(deptno) OVER (PARTITION BY
Deptno)
AS Dept_Count
FROM samples.emp WHERE Deptno IN
(10,30);

SELECT
ename, sal, deptno
FROM samples.emp WHERE Deptno IN (10,30)
WITH COUNT(Deptno ) (TITLE 'Total_Count') by deptno;

SELECT empno, ename , sal,deptno


, SUM(sal) OVER (PARTITION BY deptno)
FROM samples.emp;

SELECT empno, ename, sal, deptno


FROM samples.emp
WITH SUM(sal) BY deptno;

create table salestbl


(
storeid int , prodid char , sales
decimal(9,2)
);
insert
insert
insert
insert
insert
insert

into
into
into
into
into
into

salestbl
salestbl
salestbl
salestbl
salestbl
salestbl

values
values
values
values
values
values

(1001,'A',5674.00);
(1001,'B',7634.00);
(1001,'A',2634.00);
(1001,'C',1674.00);
(1001,'A',6000.00);
(1001,'B',2100.00);

insert
insert
insert
insert
insert

into
into
into
into
into

salestbl
salestbl
salestbl
salestbl
salestbl

values
values
values
values
values

(1002,'A',5674.00);
(1002,'B',5674.00);
(1002,'A',2000.00);
(1002,'C',5674.00);
(1002,'C',3000.00);

insert into salestbl values (1003,'A',5674.00);


insert into salestbl values (1003,'A',5674.00);

SELECT storeid , prodid , sales


, SUM(sales) OVER (PARTITION BY storeid)
FROM samples.salestbl ORDER BY 1,2;

SELECT storeid , prodid , sales


FROM samples.salestbl
WITH SUM(sales) BY storeid ORDER BY
1,2;

SELECT storeid , prodid, sales


with SUM(sales) FROM
samples.salestbl
ORDER BY 1, 2;

SELECT storeid , prodid, sales


, SUM(sales) OVER ( )
FROM samples.salestbl ORDER BY 1,2;

Teradata Extension
Alternative
An alternative Teradata shortcut extension is the CSUM
function which can produce the same results, however
does not comply with ANSI standards.

CSUM ( colname, sort_item1, sort_item2,


)
Results are sorted in ascending order based on the
specified sort list columns. Descending sorts of any of
the sort list columns may be specified by using the
DESC Qualifier.

CREATE TABLE daily_sales


(
itemid INTEGER,
salesdate DATE FORMAT 'YY/MM/DD',
sales DECIMAL(9,2)
) PRIMARY INDEX ( itemid );
insert into daily_sales
04',1005.00);
insert into daily_sales
05',5000.00);
insert into daily_sales
04',1005.00);
insert into daily_sales
06',2205.00);
insert into daily_sales
04',3005.00);

values ( 10,'1999-02values ( 10,'1999-02values ( 20,'1999-02values ( 10,'1999-02values ( 30,'1999-02-

The cumulative sum function computes a


running or cumulative total of a columns value
SELECT salesdate, sales,
SUM(sales) OVER (ORDER BY salesdate
ROWS UNBOUNDED PRECEDING)
AS "Csum" FROM samples.daily_sales WHERE salesdate
BETWEEN DATE '1999-01-01' AND DATE '1999-12-31';

-- Query with out " ROWS UNBOUNDED PRECEDING "


SELECT salesdate, sales, SUM(sales) OVER (order by
salesdate )
AS "Csum" FROM samples.daily_sales
WHERE salesdate
BETWEEN DATE '1999-01-01' AND DATE '1999-12-31';

SELECT salesdate
, sales , EXTRACT(MONTH FROM salesdate) AS Mon
,SUM(sales) OVER (PARTITION BY Mon ORDER BY
salesdate
ROWS UNBOUNDED PRECEDING) AS "Csum"
FROM samples.daily_sales WHERE itemid = 10
AND EXTRACT( YEAR FROM salesdate) = 1999 AND
Mon in (1,2);

SELECT salesdate, itemid, sales


, MSUM(sales, 3, salesdate) AS "Msum"
FROM samples.daily_sales
WHERE itemid = 10
AND EXTRACT(YEAR FROM salesdate) = 1999
AND EXTRACT(MONTH FROM salesdate) IN
(1,2);

SELECT salesdate , itemid , sales


, SUM(sales) OVER (ORDER BY salesdate
ROWS 2 PRECEDING) AS "Msum"
FROM samples.daily_sales
WHERE itemid = 10
AND EXTRACT(YEAR FROM salesdate) = 1999
AND EXTRACT(MONTH FROM salesdate) IN
(1,2);

Example: Produce a listing showing a weekly moving


average of sales revenue for the first two months of
1999. Use a width of 7. Use the Teradata MAVG function

SELECT salesdate, itemid, sales,


EXTRACT(MONTH FROM salesdate) as mon,
MAVG(sales, 2, salesdate) AS "MAvg"
FROM samples.daily_sales WHERE itemid =
10
AND EXTRACT(YEAR FROM salesdate)
=1999
AND EXTRACT(MONTH FROM salesdate) IN
(1,2);

SELECT salesdate, itemid, sales


, AVG(sales) OVER (ORDER BY salesdate
ROWS 6 PRECEDING) AS "MAvg"
FROM samples.daily_sales WHERE itemid = 10
AND EXTRACT(YEAR FROM salesdate) = 1999
AND EXTRACT(MONTH FROM salesdate) IN (1,2);

SELECT salesdate
,CAST(itemid AS BYTEINT) (FORMAT '99') AS "itemid"
,sales
,CSUM(sales, salesdate) AS "CSUM"
,MSUM(sales, 3, salesdate) AS "MSUM"
,MDIFF(sales, 3, salesdate) AS "MDIFF"
,MAVG(sales, 3, salesdate) AS "MAVG"
FROM samples.daily_sales WHERE salesdate BETWEEN 990101
AND 991231;

Ordered Analytic
Function Types

SELECT storeid, prodid, sales,


SUM(sales) OVER (ORDER BY sales
DESC)
FROM salestbl;
SELECT storeid, prodid, sales,
SUM(sales) OVER (PARTITION BY prodid
ORDER BY sales DESC)
FROM salestbl ;
SELECT storeid, prodid, sales,
SUM(sales) OVER (PARTITION BY prodid
ORDER BY sales DESC) AS ProdSum
FROM salestbl QUALIFY ProdSum >=
1500;

SELECT storeid, prodid, sales,


MIN(sales)OVER (PARTITION BY
storeid ORDER BY sales DESC)
FROM salestbl;
SELECT storeid, prodid, sales,
MAX(sales)OVER (PARTITION BY
storeid
ORDER BY sales DESC)
FROM salestbl;

hanced Numeric Formatting Optio

Radix and Group Separators


The following query uses SDF( Specification for Data formating )
conventions todefine a format for the output. These conventions
must be defined in the SDF file using the tdlocaldefutility.
SELECT salary_amount (FORMAT 'G-(10)D9(2)')
FROM employee
WHERE employee_number = 801;
salary_amount
-------------100,000.00
G- Represents the GROUP SEPARATOR as defined in the SDF. In U.S.
applications,
this is usually a comma (,) character. It isused to separate digits of
the whole number
into groups of three or less. It must always appear as the first
Note:
character in a FORMAT
SDF
symbols
may not bethe
mixed
in the
same FORMAT
string
withSDF. Radix
string.
D- Represents
RADIX
symbol
as defined
in the
explicit
FORMAT
separates
the whole number from the fractional part. In U.S.
designations. For example, you cannot have 'D' and an explicit '.' in

Integers, Fractions and Zero-suppression


The same output may be achieved using the
following formatting example:
SELECT salary_amount (FORMAT 'G-Z(I)D9(F)')
FROM employee
WHERE employee_number = 801;
salary_amount
-------------100,000.00
F- Represents the number ofcharacters
needed to display the fraction portion of
numeric data. In the case of a DEC(10,2) data
type, 9(F) is equivalent to 9(2).
I - Represents the number of characters
needed to display the INTEGER portion of
numeric data. In the case of a DEC(10,2) data
type, I is equivalent to 9(8).
Z- Represents zero-suppressed decimal digit.
Z(I) represents a zero-suppressed
integer. Floating zero-suppression may also
be specified using multiple Z's (ZZZZZZ).

Fixed Currency Options


The following examplesdemonstrate the ability to
customize formats to accomdate a variety of
international conventions for representing currency
amounts. Fixed Currency
SELECT salary (FORMAT 'GL9(I)D9(F)')
FROM retail.employee
WHERE phone=7901659353;
---------------------$00,100,000.00
L- Represents the CURRENCY SYMBOL as defined
in the SDF. In U.S. applications, this is usually
the dollar ($) symbol. A single 'L' indicates a
fixed (i.e. non-floating)
currency symbol.
SELECT salary (FORMAT 'GZ(I)D9(F)L')
FROM retail.employee
WHERE phone=7901659353;

Timestamp

Sub Queries

Usually, a subquery should return only


one record, but sometimes it can also
return multiple records when used with
operators like IN, NOT IN in the where
SELECT Empno, ename
clause.
FROM Emp WHERE deptno IN
(10,30);
SELECT Empno, ename
FROM Emp WHERE job IN (SELECT
job
FROM Emp WHERE job=
'Salesman');

Correlated Subquery
The inner query and the outer query are
interdependent. For every row processed
by the inner query, the outer query is
processed as well. The inner query depends
on the outer query before it can be
processed.
SELECT p.product_name FROM
product p
WHERE p.product_id = (SELECT
o.product_id FROM order_items o
WHERE o.product_id =
p.product_id);

SELECT ename,deptno ,sal


FROM emp
WHERE sal = (SELECT MAX (sal)
FROM emp e WHERE e.deptno =
e.deptno);

SELECT ename ,sal FROM emp


e
WHERE sal > (SELECT AVG (sal)
FROM emp e WHERE e.deptno=
e.deptno);

SELECT d.mgr AS
mgr_emp_#,d.deptno,e.sal
FROM emp d INNER JOIN emp e
ON e.empno =d.mgr
WHERE e.sal = (SELECT MAX (sal)
FROM emp e WHERE d.deptno=
e.deptno);

EXIST
Operator

SELECT 'There are employees'


AS Answer WHERE EXISTS
(SELECT * FROM emp WHERE
deptno = 40);
SELECT 'There are employees'
AS Answer WHERE not EXISTS
(SELECT * FROM emp WHERE
deptno = 40);

Ranking

Você também pode gostar