选择语句计算列的问题,包括总和和组

时间:2015-02-09 07:52:32

标签: sql-server select group-by sum

我正在尝试做一个看似基本的select语句,但无法使where子句的语法正确。

select 
    T1.CUSTNMBR [Customer Number],
    T1.APFRDCTY [Doc Type],
    sum(T1.APPTOAMT) as [Apply to Amount],
    T1.APFRDCNM [Apply From Doc No],
    T2.ORTRXAMT [Doc Amount],
    T2.CURTRXAM [Unapplied Amount]
from 
(
    select 
        CUSTNMBR, 
        APFRDCNM, 
        APFRDCTY, 
        APPTOAMT
    from GPSTJ..RM30201
    union 
    select 
        CUSTNMBR as CUSTNMBR, 
        APFRDCNM as APFRDCNM,
        APFRDCTY as APFRDCTY,
        APPTOAMT as APPTOAMT    
    from GPSTJ..RM20201
) T1
LEFT JOIN 
(
    select 
        CUSTNMBR, 
        DOCNUMBR, 
        DOCDATE, 
        RMDTYPAL, 
        ORTRXAMT, 
        CURTRXAM     
    from GPSTJ..RM20101
    union
    select
        CUSTNMBR as CUSTNMBR, 
        DOCNUMBR as DOCNUMBR, 
        DOCDATE as  DOCDATE, 
        RMDTYPAL as RMDTYPAL, 
        ORTRXAMT as ORTRXAMT, 
        CURTRXAM as CURTRXAM 
    from GPSTJ..RM30101
) T2 on T1.CUSTNMBR = T2.CUSTNMBR and T1.APFRDCNM = T2.DOCNUMBR

where (sum(T1.APPTOAMT) - T2.ORTRXAMT) <> T2.CURTRXAM

group by
T1.CUSTNMBR, T1.APFRDCTY, T1.APFRDCNM, T2.ORTRXAMT, T2.CURTRXAM

如果没有where子句,查询运行正常,但结果太多了。我基本上试图从sum,sum(T1.APPTOAMT)中减去一个分组字段(T2.ORTRXAMT),但是我无法正确获得语法,它只是不起作用,并且在错误消息中没有任何线索。

1 个答案:

答案 0 :(得分:0)

在对聚合或组进行过滤时使用HAVING而不是WHERE子句

SELECT
    T1.CUSTNMBR AS [Customer Number],
    T1.APFRDCTY AS [Doc Type],
    SUM(T1.APPTOAMT) AS [Apply to Amount],
    T1.APFRDCNM AS [Apply From Doc No],
    T2.ORTRXAMT AS [Doc Amount],
    T2.CURTRXAM AS [Unapplied Amount]
FROM(
    SELECT 
        CUSTNMBR, APFRDCNM, APFRDCTY, APPTOAMT
    FROM GPSTJ..RM30201
    UNION
    SELECT
        CUSTNMBR AS CUSTNMBR, 
        APFRDCNM AS APFRDCNM,
        APFRDCTY AS APFRDCTY,
        APPTOAMT AS APPTOAMT    
    FROM GPSTJ..RM20201
)T1 
LEFT JOIN (
    SELECT 
        CUSTNMBR, DOCNUMBR, DOCDATE, RMDTYPAL, ORTRXAMT, CURTRXAM
    FROM GPSTJ..RM20101
    UNION
    SELECT
        CUSTNMBR AS CUSTNMBR, 
        DOCNUMBR AS DOCNUMBR, 
        DOCDATE AS DOCDATE, 
        RMDTYPAL AS RMDTYPAL, 
        ORTRXAMT AS ORTRXAMT, 
        CURTRXAM AS CURTRXAM 
    FROM GPSTJ..RM30101
) T2 
    ON T1.CUSTNMBR = T2.CUSTNMBR
    AND T1.APFRDCNM = T2.DOCNUMBR
GROUP BY
    T1.CUSTNMBR, T1.APFRDCTY, T1.APFRDCNM, T2.ORTRXAMT, T2.CURTRXAM
HAVING
    (SUM(T1.APPTOAMT) - T2.ORTRXAMT) <> T2.CURTRXAM