如何计算SQL中两个选择的差异(Access、JetSQL)
我需要得到两个如何计算SQL中两个选择的差异(Access、JetSQL),sql,ms-access,join,jet-sql,Sql,Ms Access,Join,Jet Sql,我需要得到两个SUM…的差值,其中来自同一个表联接的查询: 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 N
SUM…的差值,其中
来自同一个表联接的查询:
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
及
我尝试过使用UNION
,但它返回两行,而不是我可以计算的两列
我该怎么做呢?我觉得我错过了一些琐碎的事情,所以提前谢谢 这应该有效:
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
如果需要所有三个值,可以使用条件聚合:
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\u Id
为NULL
,则:
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;
谢谢,选择了@gordon linoff的解决方案
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;