减去两个子查询

时间:2013-01-18 20:07:40

标签: 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

4 个答案:

答案 0 :(得分: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

还要考虑类似

的内容
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)

答案 1 :(得分:0)

试试这个

; WITH CTE1 AS 
(
SELECT station_id, SUM(tcl_missing + tcl_not_missing) as tcl_total
 FROM tcl_missing_summary 
 GROUP BY station_id
), CTE2 AS
(
SELECT station_id, SUM(total) as total
 FROM tcl_breakdown_op
 WHERE tr_standard not like '%cru'
 GROUP BY station_id
)

SELECT * FROM CTE1 a
LEFT OUTER JOIN CTE2 b ON a.station_id = b.station_id
WHERE a.tcl_total - isnull(b.total,0) <> 0

答案 2 :(得分:0)

SELECT a.station_id AS station, a.tcl_total-b.total AS difference
(
 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.station_id = b.station_id
 WHERE a.tcl_total - b.total <> 0

如果您知道某个结果集可能没有某些子站的数据,也可以将其转换为外部联接。

答案 3 :(得分:0)

我同意关于CTE方法的rs作为嵌套选择恕我直言两个或三个之后变得讨厌。 CTE还会在逻辑上以一组一个的方式显示您的数据。

但是,如果必须使用嵌套选择,只需添加几行即可完成:

SELECT a.tcl_total
from 
(
 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 - b.total <> 0