如何计算 SQL 中两个 SELECT 的差异(Access、JetSQL)

Posted

技术标签:

【中文标题】如何计算 SQL 中两个 SELECT 的差异(Access、JetSQL)【英文标题】:How to calculate the difference of two SELECTs in SQL (Access, JetSQL) 【发布时间】:2020-04-12 11:25:59 【问题描述】:

我需要从同一个表连接中获取两个SUM...WHERE 查询的区别:

SELECT SUM(Service_template.Service_fee)
FROM (Service_template LEFT JOIN Service ON Service_template.Service_Code = Service.Service_Code) LEFT JOIN Bill ON Service.Service_ID = Bill.Service_ID
WHERE Bill.Service_ID IS NOT NULL

SELECT SUM(Service_template.Service_fee)
FROM (Service_template LEFT JOIN Service ON Service_template.Service_Code = Service.Service_Code) LEFT JOIN Bill ON Service.Service_ID = Bill.Service_ID

我尝试使用UNION,但它返回两行,而不是我可以计算的两列。

我该怎么做呢?我觉得我错过了一些琐碎的事情,所以提前谢谢!

【问题讨论】:

【参考方案1】:

如果你想要所有三个值,你可以使用条件聚合:

SELECT SUM(IIF(b.Service_ID IS NOT NULL, st.Service_fee, 0)) as total_1,
       SUM(b.Service_Id) as total_2,
       SUM(IIF(b.Service_ID IS NULL, st.Service_fee, 0)) as diff      
FROM (Service_template as st LEFT JOIN
      Service as s
      ON st.Service_Code = s.Service_Code
     ) LEFT JOIN
     Bill as b
     ON s.Service_ID = b.Service_ID;

如果您只想要SUM(),其中Service_IdNULL,那么:

SELECT SUM(b.Service_Id) as diff      
FROM (Service_template as st LEFT JOIN
      Service as s
      ON st.Service_Code = s.Service_Code
     ) LEFT JOIN
     Bill as b
     ON s.Service_ID = b.Service_ID
WHERE b.Service_ID IS NULL;

【讨论】:

【参考方案2】:

这应该可行:

Select
  Sum(T1.Sum1),
  Sum(T2.Sum2),
  Sum(T1.Sum1) - Sum(T2.Sum2) As Diff1,
  Sum(T2.Sum2) - Sum(T1.Sum1) As Diff2
From
  (SELECT SUM(Service_template.Service_fee) As Sum1 FROM (Service_template LEFT JOIN Service ON Service_template.Service_Code = Service.Service_Code) LEFT JOIN Bill ON Service.Service_ID = Bill.Service_ID WHERE Bill.Service_ID IS NOT NULL) As T1,
  (SELECT SUM(Service_template.Service_fee) As Sum2 FROM (Service_template LEFT JOIN Service ON Service_template.Service_Code = Service.Service_Code) LEFT JOIN Bill ON Service.Service_ID = Bill.Service_ID) As T2

【讨论】:

谢谢,选择了@gordon-linoff 的解决方案

以上是关于如何计算 SQL 中两个 SELECT 的差异(Access、JetSQL)的主要内容,如果未能解决你的问题,请参考以下文章

怎么用SQL比对两表

oracle如何比较两个表数据的差异?

如何使用 SQL 显示两个不同区域中时间戳之间的实时差异?

两个sql查询的性能差异?

如何计算两个日期之间的差异

SQLite如何计算同一张表的两个变量之间的差异[关闭]