从第二个表组中减去两个表组的总和,在sql中减去一倍

时间:2016-10-24 12:59:54

标签: sql-server

我有3张桌子

client,fees,financial

我想

  • 汇总客户'925'的所有费用(fee.fee)并减去任何付款(financial.payment)。
  • 显示客户端姓氏(client.lastname)。

费用和财务表格是客户的FK.Id通过fee.clientId和financial.clientId。

我认为这很简单,但个别陈述显示正确的金额,但加入时,由于许多费用和一次付款,他们加倍和三倍。

我已经尝试了很多不同的语句,并且对sql是新的完全难倒。

有人可以指导我一点点或帮助编写这个选择语句。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

这应该让你走上正确的道路。您可以独立于实际数据库运行以下代码。

CREATE TABLE #client 
    ( 
      id INT, 
      name NVARCHAR(10) 
    )

CREATE TABLE #fees
    (
      clientId INT ,
      fees DECIMAL(18, 2)
    )

CREATE TABLE #financials
    (
      clientId INT ,
      payment DECIMAL(18, 2)
    )

INSERT  INTO #client ( id, name )
VALUES  ( 925, N'Company A' )

INSERT  INTO #fees ( clientId , fees )
        SELECT  925 , 120.00
        UNION ALL
        SELECT  925 , 20.00
        UNION ALL
        SELECT  925 , 200.00
        UNION ALL
        SELECT  925 , 60.00

INSERT  INTO #financials ( clientId , payment)
        SELECT  925 , 125
        UNION ALL
        SELECT  925 , 250
        UNION ALL
        SELECT  925 , 75

-- total fees = 400
SELECT  clientId ,
        SUM(fees) Fees
FROM    #fees
GROUP BY clientId

-- total paid = 450
SELECT  clientId ,
        SUM(payment) Paid
FROM    #financials
GROUP BY clientId

-- Single query with difference
SELECT  c.id ,
        c.name ,
        TotalFees ,
        TotalPaid ,
        f.TotalFees - fi.TotalPaid AS FeesLessPaid
FROM    #client c
        INNER JOIN ( SELECT clientId ,
                            SUM(fees) TotalFees
                     FROM   #fees
                     GROUP BY clientId
                   ) f ON f.clientId = c.id
        INNER JOIN ( SELECT clientId ,
                            SUM(payment) TotalPaid
                     FROM   #financials
                     GROUP BY clientId
                   ) fi ON fi.clientId = c.id

DROP TABLE #client
DROP TABLE #fees
DROP TABLE #financials

产地:

id  name        TotalFees   TotalPaid   FeesLessPaid
925 Company A   400.00      450.00      -50.00

答案 1 :(得分:0)

尝试以下内容:

SELECT CO.LASTNAME,COALESCE(A.FEE,0)-COALESCE(B.PAYMENT,0) AMT_LEFT
FROM CLIENT CO
LEFT OUTER JOIN 
    (
    SELECT C.CLIENTID,SUM(F.FEE)FEE
    FROM CLIENT C
    INNER JOIN FEES F
    ON C.CLIENTID=F.CLIENTID)A
ON CO.CLIENTID=A.CLIENTID
LEFT OUTER JOIN 
    (
    SELECT C.CLIENTID,SUM(F.PAYMENT)PAYMENT
    FROM CLIENT C
    INNER JOIN FINANCIAL F
    ON C.CLIENTID=F.CLIENTID)B
ON CO.CLIENTID=B.CLIENTID