使用两个表在查询中获得总和

时间:2013-06-11 07:35:08

标签: sql-server tsql

我需要TrasactionPaymentsDetails的金额总和

    DECLARE @mydate DATETIME
SELECT @mydate = '2012-07-28'

select sum(rd.Amount) as total,rp.TransactionCode, rp.ReferenceDate,rp.TransactionFlag,rd.Amount

 from ReceiptsPayments rp,ReceiptsPaymentsDetail rd where 
ReferenceDate >= DATEADD(dd,1-day(@mydate),@mydate)
and ReferenceDate <= DATEADD(dd,0-day(DATEADD(mm,1,@mydate)),DATEADD(mm,1,@mydate))
and TransactionFlag='P';

以下是错误。请帮忙

  

Msg 8120,Level 16,State 1,Line 6 Column   “ReceiptsPaymentsDetail.TransactionCode”在选择列表中无效   因为它不包含在聚合函数或   GROUP BY子句。

3 个答案:

答案 0 :(得分:3)

您需要GROUP BY

DECLARE @mydate DATETIME

SELECT @mydate = '2012-07-28'

SELECT Sum(rd.amount) AS total,
       rp.transactioncode,
       rp.referencedate,
       rp.transactionflag
FROM   receiptspayments rp,
       INNER JOIN receiptspaymentsdetail rd ON rp.id=rd.receiptpaymentsid
WHERE  referencedate >= Dateadd(dd, 1 - Day(@mydate), @mydate)
       AND referencedate <= Dateadd(dd, 0 - Day(Dateadd(mm, 1, @mydate)),
                            Dateadd(mm, 1, @mydate))
       AND transactionflag = 'P'
GROUP  BY rp.transactioncode,
          rp.referencedate,
          rp.transactionflag;  

此外,您需要链接表格以避免使用CROSS JOIN,我认为这不是您想要的。我假设您的Id表格中有一个receiptpayments,其中FK位于receiptpaymentsdetails,因此INNER JOIN

答案 1 :(得分:1)

试试这个 -

DECLARE @mydate DATETIME
SELECT @mydate = '20120728'

SELECT  
      total = SUM(rd.Amount) 
    , rp.TransactionCode
    , rp.ReferenceDate
    , rp.TransactionFlag
FROM dbo.ReceiptsPayments rp
JOIN dbo.ReceiptsPaymentsDetail rd ON ON rp.ID = rd.ReceiptPaymentsID
WHERE ReferenceDate >= DATEADD(dd, 1 - DAY(@mydate), @mydate)
    AND ReferenceDate <= DATEADD(dd, - DAY(DATEADD(mm, 1, @mydate)), DATEADD(mm, 1, @mydate))
    AND TransactionFlag = 'P'
GROUP BY 
      rp.TransactionCode
    , rp.ReferenceDate
    , rp.TransactionFlag

答案 2 :(得分:0)

在上一个Group By条件之后,在您的Statement中添加where子句:

Group By rp.TransactionCode, rp.ReferenceDate,rp.TransactionFlag