填写 SQL 查询中缺失的字段

问题描述 投票:0回答:1

我正在尝试将预算和实际两个表中的数据合并到一个简单的表中,我可以在 Google Looker Studio 的数据透视表中使用它来比较实际值和预算。我设法将表格和财务数据结合起来,但我还想将预算表中的其他数据(例如来自实际数据的行的帐户名称)传输到新表中。我对 SQL 很陌生,我想我需要分两步完成,但我还没有找到如何做。

表格看起来像这样:

tbl实际:

日期 账户 平衡
2023-01-01 1234 100
2023-01-02 1235 -100

预算:

日期 账户 平衡 账户类型 账户组
2023-01-01 1234 150 销售 收入
2023-01-02 1245 -150 原材料 费用

现在我已经成功地将这两者与以下查询结合起来:

SELECT coalesce(a.date, b.date) as date, coalesce(a.Account, b.Account) as Account, a.Balance as Outcome, Account as Budgeted, b.AccountGroup, b.AccountType
FROM tblActual a
full outer join tblBudget b 
ON (b.date = a.date and b.Account = a.Account)
ORDER BY datum DESC

这似乎有效,我得到了这样的表格:

日期 账户 结果 预算 账户类型 账户组
2023-01-01 1234 100
2023-01-02 1245 -100
2023-01-01 1234 150 销售 收入
2023-01-02 1245 -150 原材料 费用

但是我如何确保新表中的 AccountTypes 和 AccountGroups 也填充了从 tblActuals 获取的行?这样所有行都有其正确的 AccountTypes 和 AccountGroups(如 tblBudget 中所定义)。就像下面这样:

日期 账户 结果 预算 账户类型 账户组
2023-01-01 1234 100 销售 收入
2023-01-02 1245 -100 原料 费用
2023-01-01 1234 150 销售 收入
2023-01-02 1245 -150 原材料 费用

我正在 Google BigQuery 中编写查询。任何帮助表示赞赏!

最诚挚的问候, 弗雷德

join google-bigquery looker-studio coalesce
1个回答
0
投票

从我在问题中看到的数据来看,您只需要像这样的内部连接:

SELECT
       a.date
     , a.Account
     , a.Balance as Outcome
     , b.Budgeted
     , b.AccountGroup
     , b.AccountType
FROM tblActual a
INNER JOIN tblBudget b ON b.date = a.date and b.Account = a.Account
ORDER BY
       a.date DESC
     , a.Account

但是,如果这些“日期”是时间戳(即包含不等于午夜的时间),则内部联接可能找不到任何匹配项。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.