How to compare a 7-month forward-looking data crossing 2022 and 2023 with 2019? - teradata

I have below the code:
SELECT T.postdate_debug AS POSTDATE,
(CAST(T.DEPART_DATE AS DATE FORMAT 'MM') (char(2))) AS "Month",
SUM(CASE WHEN T.dpt_date_yr_debug IN ('2019') THEN T.tot_REV ELSE 0 END) AS PY_REVENUE_THIS_WEEK,
SUM(CASE WHEN T.dpt_date_yr_debug IN (EXTRACT(YEAR FROM CURRENT_DATE)-1, EXTRACT(YEAR FROM CURRENT_DATE)) AND T.postdate_debug = CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)+1 THEN T.tot_REV ELSE 0 END) AS CY_REVENUE_THIS_WEEK,
SUM(CASE WHEN T.dpt_date_yr_debug IN (EXTRACT(YEAR FROM CURRENT_DATE)-1, EXTRACT(YEAR FROM CURRENT_DATE)) AND T.postdate_debug = CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)-6 THEN T.tot_REV ELSE 0 END) AS CY_REVENUE_LAST_WEEK,
SUM(CASE WHEN T.dpt_date_yr_debug IN (EXTRACT(YEAR FROM CURRENT_DATE)-1, EXTRACT(YEAR FROM CURRENT_DATE)) AND T.postdate_debug = CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)-13 THEN T.tot_REV ELSE 0 END) AS CY_REVENUE_TWO_WEEKS
FROM T
WHERE
(
(
(T.DEPART_DATE BETWEEN ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)+1, 0) AND ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)+1, +7) -1)
AND (T.postdate_debug=CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)+1 OR T.postdate_debug=CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)-6 OR T.postdate_debug=CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)-13)
)
OR
(
(T.DEPART_DATE BETWEEN ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)+1, -36) AND ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)+1, +7-36) -1)
AND T.postdate_debug=CURRENT_DATE - TD_DAY_OF_WEEK(CURRENT_DATE)-1095
)
)
And the outcome is:
enter image description here
My question is: when moving to next month, the 7-month forward-looking will be 7,8,9,10,11,12,1, and I would like the month of 1 data still compare with 2019-1. Any suggestion how to achieve this?

Related

derive 2 fields SPEED_UPGRADE and TV_PACKAGE from 3 tables

I need to derive 2 fields SPEED_UPGRADE and TV_PACKAGE from 3 tables. I have written code below. I am not getting correct count of 'SPEED' and 'TV' which are falling between start_dt and END_DT. rather it is giving me count of all 'SPEED' and 'TV'. Kindly optimise my query .
select <few columns>,
count (case WHEN Cast('2021-11-09 00:00:00' AS TIMESTAMP(0))
BETWEEN a.START_DT AND Coalesce(a.END_DT,Cast('9999-12-31 00:00:00' AS TIMESTAMP FORMAT 'Y4-MM-DDBHH:MI:SS')) AND b.VOUCHER_TYPE_CD='SPEED'
then 1
ELSE 0
end) SPEED_UPGRADE,
count(case WHEN Cast('2021-11-09 00:00:00' AS TIMESTAMP(0))
BETWEEN a.START_DT AND Coalesce(a.END_DT,Cast('9999-12-31 00:00:00' AS TIMESTAMP FORMAT 'Y4-MM-DDBHH:MI:SS')) AND b.VOUCHER_TYPE_CD='TV'
then 1
ELSE 0
end) TV_PACKAGE
FROM
(sel * from P0_view.edw_v_fct_subscriber_household_base where subscriber_status_cd ='Active' and billed_customer_id ='-1' and household_id >0 and household_base_dt='2021-11-09' ) f
right join P0_VIEW.EDW_V_FCT_FIXED_VOUCHER_REDEEMED a on f.CUSTOMER_ID=a.CUSTOMER_ID
left join P0_VIEW.EDW_V_DIM_FIXED_VOUCHER b on a.FIXED_VOUCHER_ID = b.FIXED_VOUCHER_ID
group by 1,2,3,4,5,6,7,8,9 ) q ;

WITH RECURSIVE looping through every day in the database and SUM number between two dates for each

I struggle with the last part below, the "with recursive". Of course I could loop over TimestampOrigin using C#, for every day in the database. Which would mean hundreds of times the same query. But it may be possible with one query using "with recursive".
Test data:
CREATE TABLE tblData(
Id INT, ComputerName TEXT, TimestampOrigin TEXT, Timestamp TEXT, Number INT
);
DELETE FROM tblData;
INSERT INTO tblData VALUES (1, "Computer1", '2021-02-10 12:00:00', '2021-02-27 12:00:00', 35);
INSERT INTO tblData VALUES (2, "Computer2", '2021-02-10 12:00:00', '2021-02-27 12:00:00', 24);
INSERT INTO tblData VALUES (3, "Computer3", '2021-02-09 12:00:00', '2021-02-26 12:00:00', 23);
INSERT INTO tblData VALUES (3, "Computer4", '2021-02-09 12:00:00', '2021-02-26 12:00:00', null);
INSERT INTO tblData VALUES (4, "Computer5", '2021-02-08 12:00:00', '2021-02-25 12:00:00', 7);
INSERT INTO tblData VALUES (5, "Computer6", '2021-02-08 12:00:00', '2021-02-25 12:00:00', 0);
INSERT INTO tblData VALUES (7, "Computer7", '2021-02-07 12:00:00', '2021-02-24 12:00:00', 9);
Query grouped by TimestampOrigin:
SELECT DATE(TimestampOrigin) AS TimestampOrigin,
SUM(CASE WHEN Number < 1 THEN 1 ELSE 0 END) AS Less1,
SUM(CASE WHEN Number >= 0 AND Number < 10 THEN 1 ELSE 0 END) AS Less10,
SUM(CASE WHEN Number >= 10 AND Number < 25 THEN 1 ELSE 0 END) AS Less25
FROM tblData WHERE Number NOT NULL GROUP BY DATE(TimestampOrigin) ORDER BY TimestampOrigin DESC
What I need is for every day the sum for the current up to Timestamp which is current day +17 days. Example for day 2021-02-08, sum of all rows with TimestampOrigin 2021-02-08 up to 2021-02-08 +17 days (column Timestamp).
Don't know if the extra column Timestamp which is noon time of TimestampOrigin +17 days is really required. But the over time query was the reason why I created it at the very beginning of the project.
SELECT DATE(TimestampOrigin) AS TimestampOrigin,
SUM(CASE WHEN Number < 1 THEN 1 ELSE 0 END) AS Less1,
SUM(CASE WHEN Number >= 0 AND Number < 10 THEN 1 ELSE 0 END) AS Less10,
SUM(CASE WHEN Number >= 10 AND Number < 25 THEN 1 ELSE 0 END) AS Less25
FROM tblData WHERE Number NOT NULL AND DATE(TimestampOrigin) >= DATE('2021-02-08') AND DATE(TimestampOrigin) <= DATE('2021-02-08', '+17 day')
Instead of executing the above query hundreds of times for each day and sum, I thought "with recursive" is the right approach". But was not able so far to make it work. Where to add the 17 days?
WITH RECURSIVE cte AS (
SELECT Id, ComputerName, Timestamp, DATE(Timestamp,'+1 day') totime, Number, TimestampOrigin
FROM tblData
UNION ALL
SELECT Id, ComputerName, DATE(Timestamp,'+1 day'), DATE(totime,'+1 day'), Number, TimestampOrigin
FROM cte
WHERE Number NOT NULL AND DATE(Timestamp,'+1 day') < DATE('2021-02-11')
)
SELECT DATE(TimestampOrigin),
SUM(CASE WHEN Number < 1 THEN 1 ELSE 0 END) AS Less1,
SUM(CASE WHEN Number >= 0 AND Number < 10 THEN 1 ELSE 0 END) AS Less10,
SUM(CASE WHEN Number >= 10 AND Number < 25 THEN 1 ELSE 0 END) AS Less25
FROM cte GROUP BY DATE(TimestampOrigin) ORDER BY DATE(TimestampOrigin) DESC
Expected result would be (Like when I would run the above query for each of the 4 days in the test data):
There is no need for a recursive CTE.
Join the distinct TimestampOrigins to the table under your condition and aggregate:
SELECT t1.TimestampOrigin,
SUM(t2.Number < 1) AS Less1,
SUM(t2.Number >= 0 AND t2.Number < 10) AS Less10,
SUM(t2.Number >= 10 AND t2.Number < 25) AS Less25
FROM (SELECT DISTINCT DATE(TimestampOrigin) TimestampOrigin FROM tblData) t1
INNER JOIN tblData t2
ON DATE(t2.TimestampOrigin) BETWEEN t1.TimestampOrigin AND DATE(t1.TimestampOrigin, '+17 days')
GROUP BY t1.TimestampOrigin
ORDER BY t1.TimestampOrigin DESC
See the demo.
Results:
TimestampOrigin
Less1
Less10
Less25
2021-02-10
0
0
1
2021-02-09
0
0
2
2021-02-08
1
2
2
2021-02-07
1
3
2
The result was wrong. I've found that my initial query was wrong. But with the solution from #forpas it worked at the end.
Initial single query
SELECT
SUM(Number < 1) AS Less1,
SUM(Number >= 1 AND Number < 10) AS Less10,
SUM(Number >= 10 AND Number < 25) AS Less25
FROM tblPCHardwareInformation WHERE UniqueInventoryKey IN
(
SELECT UniqueInventoryKey FROM tblPCHardwareInformation WHERE Number NOT NULL AND DATE(Timestamp) BETWEEN DATE('2020-10-09') AND DATE('2020-10-09', '+17 day') GROUP BY ComputerName ORDER BY Timestamp DESC
)
Result:
SELECT t1.TimestampOrigin,
SUM(t2.Number < 1) AS Less1,
SUM(t2.Number >= 1 AND t2.Number < 10) AS Less10,
SUM(t2.Number >= 10 AND t2.Number < 25) AS Less25
FROM (SELECT DISTINCT DATE(TimestampOrigin) TimestampOrigin FROM tblPCHardwareInformation) t1
INNER JOIN tblPCHardwareInformation t2
ON UniqueInventoryKey IN
(
SELECT UniqueInventoryKey FROM tblPCHardwareInformation WHERE Number NOT NULL AND DATE(Timestamp) BETWEEN DATE(t1.TimestampOrigin) AND DATE(t1.TimestampOrigin, '+17 day') GROUP BY ComputerName ORDER BY Timestamp DESC
)
GROUP BY t1.TimestampOrigin
ORDER BY t1.TimestampOrigin DESC

two counts in the same row

is't possible to set 2 counts in the same row.
my result from query is like this:
enter image description here
and i will that the end result seem like this :
enter image description here
and at the end build the precent count1 to count2
my attempt trough case was not successful : SELECT Date,Shift , CASE description WHEN 'Defects' THEN count ELSE 0 END AS Defect_Count , CASE description WHEN 'Total' THEN count ELSE 0 END AS Total_Count FROM ("Queries union)
Here you go. Hope this helps. Thanks.
MYSQL:
select
t.dates, t.shift,
sum(case when t.description = 'Defects' then t.counts else 0 end) as `Defects`,
sum(case when t.description = 'Total' then t.counts else 0 end) as `Total`
from (
select *
from tbl ) t
group by t.dates, t.shift
order by t.dates, t.shift
ORACLE:
SELECT dates, shift, defects , total
FROM
(
SELECT *
FROM tbl
)
PIVOT
(
sum(counts)
FOR description IN ('Defects' as defects, 'Total' as total)
)
ORDER BY dates
Result:
dates shift Defects Total
2018-01-20 AM 21 56
2018-01-20 PM 19 54
2018-01-23 AM 16 58
2018-01-23 PM 20 45
many Thanks is working for the first Step (counts in the same Row).
i will try now to build the percent (Defects to Total).
Thanks.
to build the percent (defects to Total):
select dates,shift,defects,total,round((100*defects/total),2) Percent2Total from(select t.dates, t.shift,
sum(case when t.description = 'Defects' then t.counts else 0 end) as 'Defects',
sum(case when t.description = 'total' then t.counts else 0 end) as 'Total'
from (
select *
from tbl ) t
group by t.dates, t.shift
)q order by dates,Shift.
may be it's possible to build that only with Pivot or?

TERADATA case when statement in WHERE clause

I need to write a case statement in the WHERE clause, which is -
when current_date is 1st of Month then select data BETWEEN 1st day of prev month AND last day prev month
ELSE FROM 1st of Curr month till date. I have written this so far but it is not working. '05/01/2017' will be input date.
SELECT *
FROM MyTable
WHERE calendar_date
BETWEEN
CASE WHEN extract (day from CAST( '05/01/2017' AS DATE FORMAT 'MM/DD/YYYY')) =1 --check to see date is 1st of month
THEN ADD_MONTHS((CAST( '05/01/2017' AS DATE FORMAT 'MM/DD/YYYY') - EXTRACT(DAY FROM CAST( '05/01/2017' AS DATE FORMAT 'MM/DD/YYYY'))+1), -1) --1st of prev month
AND ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_date), 0 ) --last day prev month
ELSE CAST( '05/01/2017' AS DATE FORMAT 'MM/DD/YYYY') - EXTRACT(DAY FROM CAST( '05/01/2017' AS DATE FORMAT 'MM/DD/YYYY'))+1, 0) --else 1st of Curr mont
AND CURRENT_DATE
end
order by calendar_date
select *
from mytable
where calendar_date between case
when td_day_of_month (current_date) = 1
then current_date - interval '1' month
else td_month_begin (current_date)
end
and case
when td_day_of_month (current_date) = 1
then current_date - 1
else current_date
end
order by calendar_date
#Dudu, based on your suggestion, I was able to solve the sql. here it is:
SELECT * FROM MYTABLE
WHERE CALENDAR_DATE
BETWEEN
CASE WHEN extract (day from CAST( '05/15/2017' AS DATE FORMAT 'MM/DD/YYYY')) = 1
THEN (ADD_MONTHS((CAST( '05/15/2017' AS DATE FORMAT 'MM/DD/YYYY') - EXTRACT(DAY FROM CAST( '05/15/2017' AS DATE FORMAT 'MM/DD/YYYY'))+1), -1) )
ELSE ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)+1, 0)
END
AND
CASE WHEN extract (day from CAST( '05/15/2017' AS DATE FORMAT 'MM/DD/YYYY')) > 1
THEN CURRENT_DATE
ELSE ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY FROM CURRENT_date), 0 )
END
AND REPORTNAME_MASTER_ID IN (2565,5216,5364)
order by CALENDAR_DATE

encountered ")." was expecting one of "as" in teradata

I am getting above mentioned error while executing a query against Teradata Studio express
select
Union16.Item as Item,
Union16.Description as Description,
Union16.Nbr_Trans as Nbr_Trans,
Union16.Unit_price as Unit_price,
Union16.Amount as Amount,
MIN(Union16.Amount) as Total_Amount_
from (select AL1.ticket_document_number as ticket_document_number,
AL1.transaction_code as transaction_code,
AL1.void_status as void_status,
AL1.transaction_date as transaction_date,
AL1.pnr_record_locator as pnr_record_locator,
AL1.settlement_base_fare_amt as settlement_base_fare_amt,
AL1.settlement_total_tax_amt as settlement_total_tax_amt,
AL1.Multiplier as Multiplier,
(AL1.Multiplier * 2) as Service_Incentive_Fee,
(AL1.Multiplier * 2) as Transaction_Fee,
(case when AL1.TRANSACTION_CODE = 'ET' and AL1.VOID_STATUS = 'N' then 1
when AL1.TRANSACTION_CODE = 'RF' and AL1.VOID_STATUS = 'N' then -1
else 0
end) as NetTrans,
0 as Comm_Amount,
SUM(1) as Total_Trans,
AL1.period_end_date as period_end_date,
SUM(NetTrans * 2) as Service_Fee_due,
AL1.airline_code as airline_code,
1 as Item,
(('Supplier Link Service Incentive Fee # $' || '2') || '/Tix') as Description,
2 as Unit_price,
SUM(NetTrans * 2) as Amount,
SUM(NetTrans * 2) as Transaction_Fee_due,
SUM((NetTrans * 2) + (NetTrans * 2)) as Total_Due,
SUM(1) as Total_Total_Trans_,
SUM(NetTrans * 2) as Total_Service_Fee_due_,
SUM(NetTrans * 2) as Total_Transaction_Fee_due_,
SUM((NetTrans * 2) + (NetTrans* 2)) as Total_Total_Due_,
SUM(NetTrans) as Net_Trans,
SUM(NetTrans) as Total_Net_Trans_,
SUM(NetTrans) as Nbr_Trans
from (SELECT LAST_DAY(AL1.period_end_date) AS PEDHEADER,
AL1.TICKET_DOCUMENT_NUMBER as TICKET_DOCUMENT_NUMBER ,
(case when AL1.TRANSACTION_CODE = 'ET' and AL1.VOID_STATUS = 'N' then 1
when AL1.TRANSACTION_CODE = 'RF' and AL1.VOID_STATUS = 'N' then -1
else 0
end) as NetTrans,
(case
when AL1.VOID_STATUS = 'V' then 0
when AL1.VOID_STATUS <> 'V' and AL1.TRANSACTION_CODE in ('AT','ET') then 1
when AL1.VOID_STATUS <> 'V' and AL1.TRANSACTION_CODE = 'RF' then -1
when AL1.VOID_STATUS <> 'V' and AL1.TRANSACTION_CODE not in ('AT','ET','RF') then 0
end
) as Multiplier,
AL1.TRANSACTION_CODE as TRANSACTION_CODE ,
AL1.VOID_STATUS as VOID_STATUS,
cast(AL1.TRANSACTION_DATE as date) as TRANSACTION_DATE ,
AL1.PNR_RECORD_LOCATOR as PNR_RECORD_LOCATOR ,
AL1.SETTLEMENT_BASE_FARE_AMT as SETTLEMENT_BASE_FARE_AMT ,
AL1.SETTLEMENT_TOTAL_TAX_AMT as SETTLEMENT_TOTAL_TAX_AMT,
cast(AL1.PERIOD_END_DATE as date) as PERIOD_END_DATE ,
AL1.AIRLINE_CODE as AIRLINE_CODE,
airline_name as airline_name ,
SUM (1 ) as Total_records,
0 as Total_comm_due,
SUM ((Multiplier * 2) ) as total_serv_inc_fee,
SUM ((Multiplier * 2) ) as total_trans_fee_due,
((0 + SUM((Multiplier * 2) )) + SUM((Multiplier * 2) )) as Total_amt_due,
0 as Comm_Amount,
(Multiplier * 2) as Service_Incentive_Fee,
(Multiplier * 2) as Transaction_Fee,
1 as cntr
FROM ODS_VIEWS.BOP_ARC_SETTLEMENT AL1
LEFT OUTER JOIN
(select tabC.refvalcode, tabC.acct_cd, tabC.airline_name, tabC.refvaltm
from (select ref1.refvalcode , max(case when ref1.refvalattribcode='numericCode' then ref1.refvalvalue else null end) as acct_cd,
max(case when ref1.refvalattribcode='Codedescription' then ref1.refvalvalue else null end) as airline_name,
tabA.refvaltm
from bial.refvalue ref1, (select refvalcode, refvalvalue as airline_name, max(refvalueid) as "refvaltm"
from bial.refvalue
where refvalcodesetcode='Carrier'
and refvalattribcode='Codedescription'
group by refvalcode, refvalvalue) tabA
where tabA.refvalcode = ref1.refvalcode
and ref1.refvalcodesetcode='Carrier'
group by ref1.refvalcode, tabA.refvaltm ) tabC
,
(select tabB.acct_cd, max(tabB.refvaltm) as "refvaltm"
from (select ref1.refvalcode , max(case when ref1.refvalattribcode='numericCode' then ref1.refvalvalue else null end) as acct_cd,
max(case when ref1.refvalattribcode='Codedescription' then ref1.refvalvalue else null end) as airline_name,tabA.refvaltm
from bial.refvalue ref1, (select refvalcode, refvalvalue as airline_name, max(refvalueid) as "refvaltm"
from bial.refvalue
where refvalcodesetcode='Carrier'
and refvalattribcode='Codedescription'
group by refvalcode, refvalvalue) tabA
where tabA.refvalcode = ref1.refvalcode
and ref1.refvalcodesetcode='Carrier'
group by ref1.refvalcode, tabA.refvaltm ) tabB
group by tabB.acct_cd
) tabD
where tabC.refvaltm = tabD.refvaltm
and tabC.acct_cd = tabD.acct_cd
) AIRDET
ON AL1.AIRLINE_CODE = AIRDET.acct_cd
WHERE cast(AL1.PERIOD_END_DATE as date) BETWEEN 01-01-2015 AND 31-01-2015
AND AL1.FILE_TYPE='AM'
AND AL1.SUPPLIER_LINK_INDICATOR='D'
AND AIRLINE_NAME = 'Alaska Airlines'
AND AL1.oltp_deleted_timestamp IS NULL
group by
AL1.period_end_date ,
AL1.TICKET_DOCUMENT_NUMBER,
NetTrans ,
Multiplier ,
AL1.TRANSACTION_CODE,
AL1.VOID_STATUS,
AL1.TRANSACTION_DATE,
AL1.PNR_RECORD_LOCATOR,
AL1.SETTLEMENT_BASE_FARE_AMT,
AL1.SETTLEMENT_TOTAL_TAX_AMT,
AL1.AIRLINE_CODE,
airline_name,
Total_comm_due,
Comm_Amount,
Service_Incentive_Fee,
Transaction_Fee,
cntr,
AL1.oltp_deleted_timestamp,
AL1.SUPPLIER_LINK_INDICATOR,
AL1.FILE_TYPE,
AL1.AIRLINE_CODE
)
) Union16
group by
Union16.Item,
Union16.Description,
Union16.Nbr_Trans,
Union16.Unit_price,
Union16.Amount
order by
Item asc,
Description asc;
Simply you have close look at the query editor. You will notice that Teradata Studio marks the position of the error.
There's an alias missing for the Derived Table before ) Union16

Resources