我对Teradata SQL有一个特定的问题,我肯定有一个与相关子查询有关的答案......
基本上,在我工作的呼叫中心,每个座席都必须为他们所进行的每次通话制作案例(在公司CRM中),并且每个案件都与一个帐户相关联。我需要在特定日期为所有案例创建一组代理,然后在接下来的3天内获取在这些帐户上创建的下一个案例(如果有)。基本上我需要采取以下措施 (注意所有案例都会被转移到同一个DB中,无论创建者或帐号是多少):
SELECT
CASES.CASE_ID, CASES.CREATION_TIMESTAMP, CASES.ACCOUNT_NUMBER, CASES.AGENT_ID
FROM
CASES
WHERE CREATION_DATE = {d '2013-12-01'} AND AGENT_ID IN ('aaaaa','bbbbb','ccccc')
并以某种方式为每个帐户创建的下一个案例的案例ID和创建时间戳添加2列,如下所示:
SELECT
INITIAL_CASES.CASE_ID, INITIAL_CASES.CREATION_TIMESTAMP,
INITIAL_CASES.ACCOUNT_NUMBER,
INITIAL_CASES.AGENT_ID,
REPEAT.CASE_ID, REPEAT.CREATION_TIMESTAMP
FROM
CASES AS INITIAL_CASES
LEFT JOIN
(SELECT
ACCOUNT_NUMBER, MIN(CREATION_TIMESTAMP)
FROM CASES
WHERE CREATION_TIMESTAMP > INITIAL_CASES.CREATION_TIMESTAMP
AND CREATION_DATE >= {d '2013-12-01'}
AND CREATION_DATE <= {d '2013-12-04'}) REPEAT
ON INITAL_CASES.ACCOUNT_NUMBER = REPEAT_CASES.ACCOUNT_NUMBER
WHERE AGENT_ID IN ('aaaaa','bbbbb','ccccc')
有些捕获是1)在我的代理创建他的案例之后,在同一帐户上可能没有或超过1个案例,因此我需要使用MIN(CREATION_TS)和WHERE CREATION_TS&gt;的组合。 INITIAL_CREATION_TS但是,我的代理案例的初始结果集中的每一行都需要执行此查询,因为它们都有不同的时间戳。
答案 0 :(得分:3)
您可能不需要自联接,似乎您只需要基于CREATION_TIMESTAMP的下一行数据(如果它在接下来的3天内)并且使用Windowed Aggregates很容易:
SELECT
CASES.CASE_ID, CASES.CREATION_TIMESTAMP, CASES.ACCOUNT_NUMBER, CASES.AGENT_ID,
CASE
WHEN MIN(CREATION_DATE)
OVER (PARTITION BY ACCOUNT_NUMBER
ORDER BY CREATION_TIMESTAMP
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) <= DATE '2013-12-04'
THEN MIN(CASE_ID)
OVER (PARTITION BY ACCOUNT_NUMBER
ORDER BY CREATION_TIMESTAMP
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_CASE_ID,
CASE
WHEN MIN(CREATION_DATE)
OVER (PARTITION BY ACCOUNT_NUMBER
ORDER BY CREATION_TIMESTAMP
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) <= DATE '2013-12-04'
THEN MIN(CREATION_TIMESTAMP)
OVER (PARTITION BY ACCOUNT_NUMBER
ORDER BY CREATION_TIMESTAMP
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_CREATION_TIMESTAMP
FROM
CASES
WHERE CREATION_DATE = {d '2013-12-01'} AND AGENT_ID IN ('aaaaa','bbbbb','ccccc')