2016-01-28 22 views
0

我需要顯示來自三個表的數據,只顯示有限的鏈接數據。使用多個表分組/限制結果

表的例子 -
客戶:客戶名稱,客戶ID
賬戶:帳戶名,帳戶ID,客戶ID
交易:TransactionAmount,TransactionDate,TransactionID的,帳戶ID,客戶ID

客戶可能沒有任何鏈接的帳戶,但可以有多個。 帳戶可能沒有任何鏈接事務,但可能有多個。

有兩個必需的顯示數據的方式:一是通過TransactionDate,

  1. 200強的交易,但每個帳戶只有一個(最近TransactionDate)。顯示CustomerName,AccountName,TransactionAmount。

  2. 搜索結果Customername或AccountName或TransactionID。
    a。如果按CustomerName搜索,則僅顯示CustomerName,AccountName僅具有最高AccountID,並僅使用最近TransactionDate加上相關TransactionAmount。客戶可能沒有任何賬戶或交易。 b。如果按AccountName搜索,則僅使用最近的TransactionDate顯示CustomerName,AccountName和相關的TransactionAmount。客戶可能沒有任何交易。
    c。如果按TransactionID搜索,則顯示CustomerName,AccountName和TransactionAmount。 (這個很簡單)

我很難搞清楚如何根據需要限制數據所需的分組和其他集合函數。 任何幫助將非常感激。

+0

你帶來多少SQL到目前爲止,並沒有你會得到什麼結果? – PKatona

回答

0

1),以限制交易到最新的,你可以這樣做

with LatestTransactionByAccount as (
    select * from Transactions t 
    where not exists (
    select 1 from Transactions t2 where t2.AccountID = t.AccountID 
    and t2.TransactionDate < t.TransactionDate) 
) 
select ... 
from LatestTransactionByAccount 
join ... 

2)的工作方式類似於