【问题标题】:How can I join one table with another and count the number of registers of an item per day?如何将一张桌子与另一张桌子连接起来并计算每天的物品登记数量?
【发布时间】:2021-11-03 19:12:42
【问题描述】:

我在这里遇到了一个问题。我有两张表:一张是产品和仓库员工检查的日期(date_checked),另一张是销售数据,如下所示:

PRODUCTS
    date_checked |  product_name       | category       | product_id
_____________________________________________________________________
0   2021-01-01   |  tv                 | entertainment  | 100
1   2021-01-03   |  laptop             | business       | 110
SALES
    sale_date    |  product_name       | category       | product_id
_____________________________________________________________________
0   2021-01-01   |  tv                 | entertainment  | 100
1   2021-01-01   |  laptop             | business       | 110
2   2021-01-01   |  tv                 | entertainment  | 100
3   2021-01-01   |  laptop             | business       | 110
4   2021-01-01   |  tv                 | entertainment  | 100
5   2021-01-03   |  laptop             | business       | 110
6   2021-01-03   |  tv                 | entertainment  | 100
7   2021-01-03   |  laptop             | business       | 110
7   2021-01-03   |  laptop             | business       | 110

我的目标是创建一个新表,其中包含 PRODUCTS 表的所有数据以及 date_checked 中售出的产品数量。例如:电视产品于 1 月 1 日进行了检查,当天售出了 3 台电视。笔记本电脑于 1 月 3 日进行了检查,当天售出了 3 台笔记本电脑,您可以在此处看到:

SALES_AT_CHECK_DAY
    date_checked |  product_name       | category       | product_id | sales
_____________________________________________________________________________
0   2021-01-01   |  tv                 | entertainment  | 100        | 3
1   2021-01-03   |  laptop             | business       | 110        | 3

我知道我需要在这里使用联接,但我无法计算在某一天售出了多少产品。你们能帮帮我吗?

非常感谢?

【问题讨论】:

    标签: sql database join databricks


    【解决方案1】:

    首先,您的数据模型似乎很差,因为您在两个表之间重复列。您应该只有sales 中的主键,然后查找其他信息。

    select p.date_checked, s.product_name, s.category, s.product_id, 
           count(*) as sales
    from sales s join
         products p
         on s.product_id = p.product_id and
            s.sale_date = p.date_checked
    group by p.date_checked, s.product_name, s.category, s.product_id;
    

    【讨论】:

      【解决方案2】:
      • 先加入数据
      • Count() 将根据提供的聚合计算行数。在我们的例子中,它是整个产品列,即产品。
      • 在 group by 中指定这些列
      select 
         products.*,
         count(*) as sales
      from sales 
      inner join products 
      on sales.product_id = products.product_id 
      and sales.sale_date = products.date_checked
      group by 
              products.date_checked,
              products.product_name, 
              products.category, 
              products.product_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        相关资源
        最近更新 更多