gpt4 book ai didi

sql - INNER JOIN 查询使用三个表返回符合条件的行的计数和总和

转载 作者:行者123 更新时间:2023-12-05 00:31:17 24 4
gpt4 key购买 nike

我正在尝试连接来自三个 SQL 表的数据。

表格采用以下格式:

客户

╔════════╗
║ CLIENT ║
╠════════╣
║ A ║
║ B ║
║ C ║
║ D ║
╚════════╝

工作时间
╔════════╦══════════╦════════╦════════════╗
║ Client ║ Work ║ Amount ║ Date ║
╠════════╬══════════╬════════╬════════════╣
║ A ║ Web Work ║ 10 ║ 2013-01-12 ║
║ B ║ Research ║ 20 ║ 2013-01-20 ║
║ A ║ Web Work ║ 15 ║ 2013-01-21 ║
║ C ║ Research ║ 10 ║ 2013-01-28 ║
╚════════╩══════════╩════════╩════════════╝

费用
╔════════╦══════════╦════════╦════════════╗
║ Client ║ Item ║ Amount ║ Date ║
╠════════╬══════════╬════════╬════════════╣
║ A ║ Software ║ 10 ║ 2013-01-12 ║
║ B ║ Software ║ 20 ║ 2013-01-20 ║
╚════════╩══════════╩════════╩════════════╝

我想要一个查询,返回每个客户的工作和费用的计数和总和,即:
╔════════╦═══════════╦═══════════╦══════════════╦══════════════╗
║ CLIENT ║ COUNTWORK ║ WORKTOTAL ║ COUNTEXPENSE ║ EXPENSETOTAL ║
╠════════╬═══════════╬═══════════╬══════════════╬══════════════╣
║ A ║ 2 ║ 25 ║ 1 ║ 10 ║
║ B ║ 1 ║ 20 ║ 1 ║ 20 ║
║ C ║ 1 ║ 10 ║ 0 ║ 0 ║
╚════════╩═══════════╩═══════════╩══════════════╩══════════════╝

到目前为止,我有以下几点:
SELECT clients.Client,
COUNT(distinct work_times.id) AS num_work,
COUNT(expenses.id) AS num_expenses
FROM
clients
INNER JOIN work_times ON work_times.Client = clients.Client
INNER JOIN expenses ON expenses.Client = work_times.Client
GROUP BY
clients.Client

这似乎是正确的,但它跳过了没有费用的客户,并且似乎将 num_expenses 乘以 num_work。我还想添加一个 WHERE 子句来指定仅返回两个日期之间的工作时间和费用。我需要对查询进行哪些更改才能获得所需的输出?

最佳答案

您需要单独计算子查询中的值。 WHERE的目的最外层查询的子句是过滤掉在一张表上至少有记录的记录。所以在这种情况下,Client D不会显示在结果列表中。

SELECT  a.*,
COALESCE(b.totalCount, 0) AS CountWork,
COALESCE(b.totalAmount, 0) AS WorkTotal,
COALESCE(c.totalCount, 0) AS CountExpense,
COALESCE(c.totalAmount, 0) AS ExpenseTotal
FROM clients A
LEFT JOIN
(
SELECT Client,
COUNT(*) totalCount,
SUM(Amount) totalAmount
FROM work_times
WHERE DATE BETWEEN '2013-01-01' AND '2013-02-01'
GROUP BY Client
) b ON a.Client = b.Client
LEFT JOIN
(
SELECT Client,
COUNT(*) totalCount,
SUM(Amount) totalAmount
FROM expenses
WHERE DATE BETWEEN '2013-01-01' AND '2013-02-01'
GROUP BY Client
) c ON a.Client = c.Client
WHERE b.Client IS NOT NULL OR
c.Client IS NOT NULL
  • SQLFiddle Demo

  • 更新
    ╔════════╦═══════════╦═══════════╦══════════════╦══════════════╗
    ║ CLIENT ║ COUNTWORK ║ WORKTOTAL ║ COUNTEXPENSE ║ EXPENSETOTAL ║
    ╠════════╬═══════════╬═══════════╬══════════════╬══════════════╣
    ║ A ║ 2 ║ 25 ║ 1 ║ 10 ║
    ║ B ║ 1 ║ 20 ║ 1 ║ 20 ║
    ║ C ║ 1 ║ 10 ║ 0 ║ 0 ║
    ╚════════╩═══════════╩═══════════╩══════════════╩══════════════╝

    关于sql - INNER JOIN 查询使用三个表返回符合条件的行的计数和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053226/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com