减去两个子查询

did*_*ido 5 sql sql-server select subquery

我有以下疑问。我想从 SUM 中减去数字,然后仅返回结果不为 0 的数字。任何帮助将不胜感激。我也有兴趣看看这是否可以在一个查询中完成。我尝试使用 HAVING 子句,但它返回了错误的结果。使用 SQL Server 2008

  SELECT 
(
 SELECT station_id, SUM(tcl_missing + tcl_not_missing) as tcl_total
 FROM tcl_missing_summary 
 GROUP BY station_id
) as a 

(
 SELECT station_id, SUM(total) as total
 FROM tcl_breakdown_op
 WHERE tr_standard not like '%cru'
 GROUP BY station_id
) as b
 WHERE a.tcl_total - total <> 0
Run Code Online (Sandbox Code Playgroud)

Bet*_*eth 4

假设您有多个 stationID,

  SELECT station_id, tcl_total, total, a.tcl_total - total as diff
from (
 SELECT station_id, SUM(tcl_missing + tcl_not_missing) AS tcl_total
 FROM tcl_missing_summary 
 GROUP BY station_id
) AS a INNER JOIN

(
 SELECT station_id, SUM(total) AS total
 FROM tcl_breakdown_op
 WHERE tr_standard NOT LIKE '%cru'
 GROUP BY station_id
) AS b
ON a.stationid = b.stationid
 WHERE a.tcl_total - total <> 0
Run Code Online (Sandbox Code Playgroud)

还考虑类似的事情

SELECT 
    station_id,
    SUM(tcl_missing + tcl_not_missing) AS sum_tcl_total,
    SUM(total) AS sum_total,
    SUM(tcl_missing + tcl_not_missing) - SUM(total) AS diff
FROM 
    tcl_missing_summary s INNER JOIN
    tcl_breakdown_op b ON
    s.station_id = b.station_id
WHERE
     tr_standard NOT LIKE '%cru'    
GROUP BY 
    station_id
HAVING
    SUM(tcl_missing + tcl_not_missing) <> SUM(total)
Run Code Online (Sandbox Code Playgroud)