4

我有以下疑问。我想从 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

4 回答 4

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)
于 2013-01-18T20:26:16.160 回答
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
于 2013-01-18T20:11:04.247 回答
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

如果您知道一个结果集可能没有站点的某些子集的数据,这也可以转换为外连接。

于 2013-01-18T20:13:48.040 回答
0

我同意 rs 关于 CTE 方法的观点,因为嵌套选择恕我直言,在其中两个或三个之后变得讨厌。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
于 2013-01-18T20:16:24.417 回答