可以使用子查询将这些查询合并为一个吗?

Can these queries be combined into one using a subquery?

一个查询按国家/地区查找汇总小计:

SELECT
    customer.country,
    SUM(i.subtotal) AS total
FROM
    invoices i
    LEFT JOIN customer ON i.customer_id = customer.id
WHERE
    status = 'Paid'
    AND datepaid BETWEEN '2020-05-01 00:00:00' AND '2020-06-01 00:00:00'
    AND customer.billing_day <> 0
    AND customer.register_date < '2020-06-01 00:00:00'
    AND customer.account_exempt = 'f'
    customer.country <> ''
GROUP BY
    customer.country;

另一个查询按州聚合美国客户的小计:

SELECT
    customer.state,
    SUM(i.subtotal) AS total
FROM
    invoices i
    LEFT JOIN customer ON i.customer_id = customer.id
WHERE
    status = 'Paid'
    AND datepaid BETWEEN '2020-05-01 00:00:00' AND '2020-06-01 00:00:00'
    AND customer.billing_day <> 0
    AND customer.register_date < '2020-06-01 00:00:00'
    AND customer.account_exempt = 'f'
    AND customer.country = 'US'
    AND customer.state <> ''
GROUP BY
    customer.state;

是否可以编写一个查询 returns 每个国家/地区的总数,如果国家/地区是美国,还可以 returns 该州的总数?我读过子查询可用于组合两个聚合函数,但我不确定如何在此处完成。

您可以在 group by 中使用两个键:

SELECT c.country,
       (CASE WHEN c.country = 'US' THEN c.state END) as state,
       SUM(i.subtotal) AS total
FROM invoices i JOIN
     customer c
     ON i.customer_id = c.id
WHERE i.status = 'Paid' AND
      i.datepaid >= '2020-05-01' AND
      i.datepaid < '2020-06-01' AND
      c.billing_day <> 0 AND
      c.register_date < '2020-06-01' AND
      c.account_exempt = 'f'
      c.country <> ''
GROUP BY c.country, (CASE WHEN c.country = 'US' THEN c.state END);

注意查询的其他更改:

  • 您的 WHERE 子句将外连接变成了内连接,因此 LEFT JOIN 具有误导性。
  • 所有列引用都是合格的。
  • 想必你希望5月份约会,所以我调整了逻辑。
  • 仅使用日期时无需包括时间。