【问题标题】:SQL: Joining two tables with ids and countsSQL:用 ids 和 counts 连接两个表
【发布时间】:2020-10-21 17:29:12
【问题描述】:

我卡在一个查询中,找不到解决方案。我有两张桌子。一个是关于用户的,另一个是关于消费者的。以下是表格示例:

用户表:

date ___ user_id ____ country 
2020 ___ ara123  _____ canada
2019 ___ ara567 ______ USA
2018 ___ ara890 ______ USA
2017 ___ ara789 ______ canada

消费表:

date ___ spender_id ____ country ___ gross_spend ___ net spend 
2020 ___ ara123  _____ Canada.   ___ 3.4 ___________ 4.5
2019 ___ ara567 ______ USA _________ 4.5 ___________ 6.7
2018 ___ abcd34 ______ USA _________ 56.5 __________ 4.3

我正在尝试以一种可以进行两次计算并将它们添加到最终表的方式连接这两个表。第一个计算是 sum(gross_spend)/count(user_ids),另一个是 (gross_spend)/(spender_id)。我还需要进行左连接以获取所有 user_ids 和来自消费者 ID 的公共 ID。但是,当我加入这两个表时,这两个计算的结果是相同的。下面是我正在寻找的表格:

date ___ user_id ____ spender_id ____ country ___ cal1 ____ cal2
2020 ___ ara123 _____ ara123    _____ Canada ____ 0.85 ____ 1.7
2019 ___ ara567 _____ ara567   _______ USA ____ 1.126 ___ 2.25
2018 ___ara890 ______ NULL ___________ USA ____ NULL ____ NULL 
2017 ___ ara789 ______NULL ___________ canada ___NULL ___NULL

我尝试了以下查询:

select a.date, a.user_id, b.spender_id, a.country, 
      (b.gross_spend)/count(distinct a.user_id),
      (b.gross_spend)/count(distinct b.spender_id)
from user_table a
LEFT JOIN spender_table b
on a.date = b.date and a.user_id = b.spender_id -- have also tried without joining on second condition
group by 1,2,3,4

我遇到的问题是,对于 cal1 和 cal2 列,所有值都变得相同。当我只添加日期、cal1 和 cal2 时,它会起作用。但是,一旦我将 spender_id 和 user_id 添加到表中,就会导致此问题。你知道我该如何解决吗? id 必须在表格中。 谢谢!

【问题讨论】:

  • 您的示例过于简单。您的第一行 cal1 假设有 4 个 (3.4/0.85) 用户,但您在 2020 年只显示了一个。如果您使用完整的数据集,您的查询是正确的;使用提供的数据集 cal1 和 cal2 应该彼此相等 - 在所有情况下都有一个或没有要除的记录

标签: sql database amazon-redshift


【解决方案1】:

您按单个 user_id 和 spender_ids 进行分组,当您这样做时,计数(不同的 user_id/spender_id)将始终为 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 2023-04-09
    • 2012-02-28
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多