Another solution or rather a slightly different solution.
-- Using Teradata SQL Assistant version 13.10 on a Teradata 13.10 system.
-- Generate Test data
Create Multiset Volatile Table InputData (
AccountType Char(12) Not Null
, Dt Date Format 'mm/dd/yyyy' Not Null
, Value1 Smallint Not Null)
Primary Index (AccountType,Value1)
On Commit Preserve Rows
; Insert Into InputData Values ('Bad','2009-01-31' ,3)
; Insert Into InputData Values ('Bad','2009-01-31',3)
; Insert Into InputData Values ('Bad','2009-02-28',2)
; Insert Into InputData Values ('Bad','2009-02-28',2)
; Insert Into InputData Values ('Bad','2009-03-31',4)
; Insert Into InputData Values ('Bad','2009-03-31',4)
; Insert Into InputData Values ('Good','2009-01-31',2)
; Insert Into InputData Values ('Good','2009-01-31',2)
; Insert Into InputData Values ('Good','2009-02-28',3)
; Insert Into InputData Values ('Good','2009-02-28',3)
; Insert Into InputData Values ('Good','2009-03-31',4)
; Insert Into InputData Values ('Good','2009-03-31',4)
; Insert Into InputData Values ('Ugly','2009-01-31',3)
; Insert Into InputData Values ('Ugly','2009-01-31',3)
; Insert Into InputData Values ('Ugly','2009-02-28',2)
; Insert Into InputData Values ('Ugly','2009-02-28',2)
; Insert Into InputData Values ('Ugly','2009-03-31',4)
; Insert Into InputData Values ('Ugly','2009-03-31',4)
;
-- Query Generator, copy the results back to the editor and then run that query.
select a as "Copy this and " , b as "this to Paste into the editor"
from (
select 'select AccountType '(varchar(100)) as a
, null(varchar(100)) as b
, 0(int) as c
from InputData
group by 1
UNION ALL
Select null(varchar(100))
, ', Sum( Case When dt = ''' || (dt(format'yyyy-mm-dd')(char(10))) || ''' Then Value1 Else 0 End ) as "' || (dt(format'yyyy-mm-dd')(char(10))) || '"'
, row_number() over ( partition by 1 order by dt ) as rn
from ( select distinct Dt from InputData ) as t1
UNION ALL
select 'from inputData group by 1 ;'
, null(varchar(100))
, 10000
from InputData
group by 1 ) as t
order by c
;
-- This is the Query Generated from the "Query Generator"
select AccountType
, Sum( Case When dt = '2009-01-31' Then Value1 Else 0 End ) as "2009-01-31"
, Sum( Case When dt = '2009-02-28' Then Value1 Else 0 End ) as "2009-02-28"
, Sum( Case When dt = '2009-03-31' Then Value1 Else 0 End ) as "2009-03-31"
from inputData group by 1 ;
--Results from the query
AccountType 2009-01-31 2009-02-28 2009-03-31
Ugly 6 4 8
Bad 6 4 8
Good 4 6 8
↧