query以不同的方式显示表中的值

bzzcjhmw  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(316)

这个问题在这里已经有答案了

来自多个表的sql和数据(6个答案)
10个月前关门了。
我有3个表(出勤、津贴和扣除额),在出勤、工资、津贴、金额、扣除额、金额列有一些记录。我想用选定的日期对这些列中的值进行“求和”。
合计值必须为
出席。wage:100
津贴。amount:150
扣除额。amount:120
但在我的查询中,值的显示非常不同。

SELECT Name, SUM(attendance.Wage), SUM(allowances.Amount), SUM(deductions.Amount) FROM employees
INNER JOIN attendance USING (EmployeeID)
INNER JOIN allowances USING (EmployeeID)
INNER JOIN deductions USING (EmployeeID)
WHERE MONTH(attendance.Date) = 6 AND YEAR(attendance.Date) = 2020 
AND
MONTH(allowances.Date) = 6 AND YEAR(allowances.Date) = 2020 
AND
MONTH(deductions.Date) = 6 AND YEAR(deductions.Date) = 2020 
GROUP BY employees.EmployeeID;

查询的输出:
出席。wage:400
津贴。amount:900
扣除额。amount:720
为什么数值会成倍增加?我该怎么修?

vc6uscn9

vc6uscn91#

因为您将从每个表和 join 是它们的倍增。
如果没有其他信息,我建议使用相关子查询:

SELECT e.Name,
       (SELECT SUM(a.Wage)
        FROM attendance a
        WHERE a.EmployeeID = e.EmployeeID AND
              a.date >= '2020-06-01' AND a.date < '2020-07-01'
       ),
       (SELECT SUM(a.Amount)
        FROM allowances a
        WHERE a.EmployeeID = e.EmployeeID AND
              a.date >= '2020-06-01' AND a.date < '2020-07-01'
       ),
       (SELECT SUM(d.Amount)
        FROM deduction d
        WHERE d.EmployeeID = e.EmployeeID AND
              d.date >= '2020-06-01' AND d.date < '2020-07-01'
       )
FROM employees e;

带索引的 (EmployeeId, date, amount/wage) 在这三个表中的每一个表中,这也应该比使用显式聚合和联接的替代方法具有更好的性能。

uxh89sit

uxh89sit2#

您需要在子查询中将聚合向下推,否则每个值的总和都会计数多次。

SELECT e.Name, ad.total_attendance, aw.total_allowances, dd.total_deductions
FROM employees e
INNER JOIN (
    SELECT EmployeeID, SUM(wage) total_attendance
    FROM attendance 
    WHERE date >= '2020-06-01' and date < '2020-07-01'
    GROUP BY EmployeeID
) ad USING (EmployeeID)
INNER JOIN (
    SELECT EmployeeID, SUM(amount) total_allowances
    FROM allowances 
    WHERE date >= '2020-06-01' and date < '2020-07-01'
    GROUP BY EmployeeID
) aw USING (EmployeeID)
INNER JOIN (
    SELECT EmployeeID, SUM(amount) total_deductions
    FROM deductions 
    WHERE date >= '2020-06-01' and date < '2020-07-01'
    GROUP BY EmployeeID
) dd USING (EmployeeID)

相关问题