我有两个SQL查询来提取数据,如下表所示:
====
查询获取表A:
SELECT :DATE AS Date, A.Tracking_ID AS Number, A.Country, COUNT(EmailID) AS EmailSent
FROM
FACT_EMAILS A
LEFT OUTER JOIN DIM_ACCOUNT B
ON A.ACCT_ID=B.ACCT_ID
WHERE A.TIMESTAMP>SYSDATE
AND A.Tracking_ID IN (‘12345’,’23416’,’7890’)
GROUP BY :DATE, A.Tracking_ID, A.Country
查询得到表B:
SELECT :DATE AS Date, A.Tracking_ID AS Number, A.Country, COUNT(EmailID) AS EmailResponse
FROM
FACT_EMAILS A
LEFT OUTER JOIN DIM_ACCOUNT B
ON A.ACCT_ID=B.ACCT_ID
INNER JOIN DIM_EMAILRESP C
ON C.Email_Type_ID = A.Email_Type_ID
WHERE C.Email_Type_ID IN (1,3,5)
AND A.TIMESTAMP>SYSDATE
AND A.Tracking_ID IN (‘12345’,’23416’,’7890’,)
GROUP BY :DATE, A.Tracking_ID, A.Country
======
背景:我使用了一个额外的表来获取表B中的输出,因为我只查找有电子邮件响应的记录。我在提取表A中的数据时没有使用此表。此外,数据库中没有表A和表B.命名仅用于描述此示例。
我的问题是如何将表A,表B和输出结合起来如表C所示。
有人可以请帮助。
让我们把你的表A和表B数据块连接起来并将它们连接在一起:
SELECT
a.date,
a.number,
a.country,
a.EmailSent,
COALESCE(b.EmailResponse,0) as EmailResponse
FROM
(
SELECT :DATE AS Date, A.Tracking_ID AS Number, A.Country, COUNT(EmailID) AS
EmailSent
FROM
FACT_EMAILS A
LEFT OUTER JOIN DIM_ACCOUNT B
ON A.ACCT_ID=B.ACCT_ID
WHERE A.TIMESTAMP>SYSDATE
AND A.Tracking_ID IN ('12345','23416','7890')
GROUP BY :DATE, A.Tracking_ID, A.Country
) a
LEFT OUTER JOIN
(
SELECT :DATE AS Date, A.Tracking_ID AS Number, A.Country, COUNT(EmailID) AS
EmailResponse
FROM
FACT_EMAILS A
LEFT OUTER JOIN DIM_ACCOUNT B
ON A.ACCT_ID=B.ACCT_ID
INNER JOIN DIM_EMAILRESP C
ON C.Email_Type_ID = A.Email_Type_ID
WHERE C.Email_Type_ID IN (1,3,5)
AND A.TIMESTAMP>SYSDATE
AND A.Tracking_ID IN ('12345','23416','7890')
GROUP BY :DATE, A.Tracking_ID, A.Country
) b
ON
a.date = b.date AND
a.Number = b.number AND
a.country = b.country
(...) a
中的所有内容都是您生成A的查询
(...) b
中的所有内容都是您生成B的查询
这两个留在公共列上。 COALESCE
用于在B中没有匹配的行数据的情况下为EmailsResponse
设置0。我在IN
条款中纠正了你的撇号
实际上,这可能可以通过更简单的查询来解决:
SELECT
:DATE AS Date,
A.Tracking_ID AS Number,
A.Country,
COUNT(A.Tracking_ID) as EmailSent,
COUNT(C.Email_Type_ID) AS EmailResponse
FROM
FACT_EMAILS A
LEFT OUTER JOIN DIM_EMAILRESP C
ON C.Email_Type_ID = A.Email_Type_ID
AND C.Email_Type_ID IN (1,3,5)
WHEREA.TIMESTAMP>SYSDATE
AND A.Tracking_ID IN ('12345','23416','7890')
GROUP BY :DATE, A.Tracking_ID, A.Country
你没有发布你所有的表结构/关系,所以我不得不猜测一些事情;就像我猜测在查询中不需要B一样 - 它似乎没有被使用