[英]How to calculate the difference of two SELECTs in SQL (Access, JetSQL)
我需要從同一個表連接中獲取兩個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
,但它返回兩行,而不是我可以進行計算的兩列。
我該怎么做go呢? 我覺得我錯過了一些微不足道的東西,所以提前謝謝!
這應該有效:
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;
如果您只想要Service_Id
為NULL
的SUM()
,那么:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.