2012-09-05 53 views
0

在我的情況下,我有三個表。合同表,協議表和付款表。我所擁有的是一張表格,其中包含代表債務價值的合同,另一個表格中包含償還債務的條件,另一個表格與協議表格有關,債務分成包裹。查詢顯示相關表的具體數值

ContractsTable 
(Id | Number | Name | Debt | ...) 
1 | 1234 | AAAAAA | 1250,00 € | ... 
2 | 1235 | BBBBBB | 5000,20 € | ... 
3 | 1236 | CCCCCC | 500,00 € | ... 

AgreementsTable 
(Id | ContractId | Debt | IsValid | ...) 
1 |  1  | 1250,00 € | 1 | ... 
2 |  2  | 5000,20 € | 0 | ... 
3 |  2  | 5000,20 € | 1 | ... 
4 |  3  | 500,00 € | 0 | ... 

PaymentsTable 
(Id | AgreementId | Date | Amount | IsPaid | ...) 
    1 |  1  | 01/08/2012 | 500,00 € | 1 | ... 
    2 |  1  | 01/09/2012 | 500,00 € | 1 | ... -> Last payment 
    3 |  1  | 01/10/2012 | 250,00 € | 0 | ... -> Next Payment 
    4 |  3  | 01/08/2012 | 1000,00 € | 1 | ... 
    5 |  3  | 01/09/2012 | 1000,00 € | 1 | ... 
    6 |  3  | 01/10/2012 | 1000,00 € | 0 | ... 
    7 |  3  | 01/11/2012 | 1000,00 € | 0 | ... 
    8 |  3  | 01/12/2012 | 1000,20 € | 0 | ... 

所以當我執行存儲過程來獲得與合同中的表,我想以某種方式看到與做最後付款日期和下次付款日期一列太做。但是,只有當合同有效且與下一次付款有效的協議有效時,我才能看到最後一次付款的日期和下一次付款的日期。

我正在使用MS Sql Server。

在此先感謝!

+0

你能提供一個你想要的數據和結果的例子嗎? –

回答

2

的日期將這項工作嗎?

select aa.Id 
     , aa.Number 
     , aa.Name 
     , aa.Debt 
     ... 
     , max(aa.Date_LastPayment) as Date_LastPayment 
     , min(aa.Date_NextPayment) as Date_NextPayment 
from  
(  
    select a.Id 
      , a.Number 
      , a.Name 
      , a.Debt 
      ... 
      , case when c.IsPaid = 1 then c.[Date] 
        else null 
        end as Date_LastPayment 
      , case when c.IsPaid = 0 then c.[Date] 
        else null 
        end as Date_NextPayment 
    from ContractsTable a 
    inner join AgreementsTable b on b.ContractId = a.Id 
    inner join PaymentsTable c on c.AgreementId = b.Id 
    where b.IsValid = 1 
) aa 
group by aa.Id 
      , aa.Number 
      , aa.Name 
      , aa.Debt 
      ... 

我用「分」爲下一步付款日期假設有多個下付款日期。

SQL Fiddle

+0

這幾乎是我所需要的,問題是因爲它顯示所有付款日期... – Miguel

+0

根據您的樣本數據,您的預期結果是什麼? –

+0

我需要得到所有沒有任何相關協議的合同。我只得到那些有積極協議的人。我正在使用MS Sql Server 2012,正如我所說的查詢不會提供與SQL小提琴相同的結果。 – Miguel

0

Max(PaymentsTable.Date)不是你要找的。
請更好地確定最後付款日期和下次付款

select ContractsTable.Id, ContractsTable.Number, ContractsTable.Debt 
, count(AgreementsTable.ID) as 'NumAgreements' 
, max(PaymentsTable.Date) 
from ContractsTable 
left outter join AgreementsTable 
on ContractsTable.ID = AgreementsTable.ID 
left outter join PaymentsTable 
on ContractsTable.ID = PaymentsTable.ID 
group by ContractsTable.Id, ContractsTable.Number, ContractsTable.Debt