在Sql Server中使用多个联接的每个组的最后记录

时间:2014-11-13 07:55:54

标签: sql sql-server entity-framework

我有3个表Customer,Bank和BankTransaction。

在我的视图中我想在银行帐户中显示每个客户的余额。

这是我的表格

   Customer

   Id   Name   
   ---------
   1    John   
   2    Jack 

   Bank

   Id   CustomerId   BankName   
   ----------------------------------
   1    1            HSBC
   2    2            HSBC 

  BankTransaction



   Id   BankID       MoneyIn   MoneyOut  Balance   
   ---------------------------------------------
   1    1            1000      0         1000
   2    1            0         500       500 
   3    2            2000      0         2000 
   4    2            2000      0         4000
   5    2            1000      0         5000     

现在我要显示以下数据视图查询

  John    500
  Jack    5000

每位客户的最后余额

2 个答案:

答案 0 :(得分:0)

使用Window function您可以获得结果。试试这个。

;WITH cte
     AS (SELECT Row_number() OVER (partition BY b.id ORDER BY a.id DESC) rn,
                c.Name,
                a.balance
         FROM   BankTransaction a
                JOIN bank b ON a.BankID = b.Id
                JOIN Customer c ON c.Id = b.CustomerId)
SELECT name, balance
FROM   cte
WHERE  rn = 1 

答案 1 :(得分:0)

试试这个

SELECT A.Name,
       Sum(C.MoneyIN) - Sum(C.MoneyOut) AS Balance
FROM   #Customer A
JOIN   #Bank B ON A.Id = B.id
JOIN   #BankTransaction C ON B.Id = C.BankID
GROUP  BY A.Name