[英]Teradata SQL code to find count between eff start and end date
I have a dataset that has 5 columns.我有一个包含 5 列的数据集。 Each account can have multiple rows.每个帐户可以有多个行。 I need to group the data by C2 and Monthyear and find counts我需要按 C2 和月年对数据进行分组并查找计数
ACC_ID, C1 , C2, EFF_START_DATE, EFF_END_DATE
111 , 0 , A , 2018-01-01, 2499-12-31
222 , 0 , A , 2018-02-15 , 2018-03-15
222 , 0 , B , 2018-03-16, 2499-12-31
333 , 0, A, 2000-01-01, 2499-12-31
I need to group this by months and find count for each month.我需要按月分组并找到每个月的计数。 So if someone has 2018-01-01 as EFF_STA_DTE and 2499-12-31 as EFF_END_DATE.因此,如果有人将 2018-01-01 作为 EFF_STA_DTE,并将 2499-12-31 作为 EFF_END_DATE。 They should be a part of all the months starting 2018.它们应该成为 2018 年开始的所有月份的一部分。
Similarly if someone has 2018-02-15 as EFF_STA_DTE and 2018-03-15 as EFF_END_DATE their count should only reflect for Feb and March 2018.同样,如果有人将 2018-02-15 作为 EFF_STA_DTE,并将 2018-03-15 作为 EFF_END_DATE,则他们的计数应该只反映 2018 年 2 月和 2018 年 3 月。
Also I am only trying to get a count starting 2018 even if eff_start_Date is in past.此外,即使 eff_start_Date 已经过去,我也只是想从 2018 年开始计算。 So 333 in above case will have count 1 in 2018 and henceforth因此,上述情况下的 333 将在 2018 年及以后计数为 1
Tried to extract Month year and do the count based on eff_start_Date but that is giving incorrect result.试图提取月年并根据 eff_start_Date 进行计数,但结果不正确。
Expected Output in above case在上述情况下预期为 Output
MONTH, C2, COUNT
JAN-18, A, 2. -- FOR ACCOUNT 111 ,333
FEB-18, A , 3. -- FOR ACCOUNT 111,222,333
MARCH-18, A, 1 -- FOR ACCOUNT 111,222,333
MARCH-18, B, 1. -- FOR ACCOUNT 222
The most efficient way utilizes Teradata's EXPAND ON
extension to Standard SQL:最有效的方法是利用 Teradata 对标准 SQL 的EXPAND ON
扩展:
WITH cte AS
(
SELECT -- first of month
Trunc(BEGIN(pd), 'mon') AS mon
,C2
FROM tab
-- create a period on-the-fly, adjust the end date as periods exclude the end
EXPAND ON PERIOD(EFF_START_DATE, Next(EFF_END_DATE)) AS pd
-- return one row per month
BY ANCHOR PERIOD MONTH_BEGIN
-- restrict output to a specifc range
FOR PERIOD (date '2018-01-01', date '2018-03-31')
)
SELECT mon, C2, Count(*)
FROM cte
GROUP BY 1,2
ORDER BY 1,2
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.