【问题标题】:How to join a subquery from two distinct select statements in postgreSQL?如何从 postgreSQL 中的两个不同的 select 语句连接子查询?
【发布时间】:2023-02-23 02:32:15
【问题描述】:

我正在尝试将 select 语句作为子查询添加到现有语句中,但我正在努力寻找将其插入的位置。目前我有两个 select 语句,我正在尝试将底部的一个作为子查询添加到顶部的一个中,而不是创建两个单独的表并将它们连接起来。

我认为我应该在括号中的顶部选择语句之后、代码的“来自”部分之前添加底部语句。是否可以创建一个表,将 ID、名称、2021 年销售额、2022 年销售额列为一个表中的四列?任何帮助表示赞赏。我确实有一个我从中提取的发票日期列,但不包括在内,因为我不希望它出现在我的最终结果中。

select customer.customerid, 
    CONCAT(customer.firstname, ' ', customer.lastname) AS full_name, invoice.total AS "2021 Sales"
    from customer
    inner join invoice
    on customer.customerid = invoice.customerid
    where invoicedate like '%2021%';


select customer.customerid, total AS "2022 Sales"
from customer
inner join invoice
on customer.customerid = invoice.customerid
where invoicedate like '%2022%'

【问题讨论】:

  • invoicedate 的数据类型是什么?向问题添加信息.
  • 大概一个客户可以有很多发票,所以大概首先你需要汇总?
  • invoicedate 的数据类型是文本
  • 所以像在客户 ID 中添加一个不同的东西?或者也许是总数

标签: postgresql subquery


【解决方案1】:

您可以使用一个查询和两个连接

select 
    customer.customerid, 
    CONCAT(customer.firstname, ' ', customer.lastname) AS full_name, 
    invoice_2021.total AS "2021 Sales",
    invoice_2022.total AS "2022 Sales"
from 
  customer
    inner join invoice invoice_2021 on 
        customer.customerid = invoice_2021.customerid and
        invoice_2021.invoicedate like '%2021%'
    inner join invoice invoice_2022 on 
        customer.customerid = invoice_2022.customerid and
        invoice_2022.invoicedate like '%2022%';

【讨论】:

  • 我只有一列用于 invoice.total,所以我不确定如何将这一列引用为两个名称(invoice_2021.total 和 invoice_2022.total)
  • 我的回答有误。我忘记了我在两个连接中都连接到同一个表,所以我需要给它们别名。我已经更正了我的答案。
猜你喜欢
  • 2013-05-27
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2022-01-02
相关资源
最近更新 更多