在我的情况下,我有三张桌子。合同表,协议表和付款表。我所拥有的是一张包含代表债务价值的合约的表格,另一张包含偿还债务条件协议的表格,以及另一张与债务分割的协议表相关的表格。
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 | ...
因此,当我执行存储过程以获取包含合同的表时,我想以某种方式查看一个列,其中包含已完成的上次付款日期以及下次付款的日期。但是,如果合同与有关协议有关,并且只有在协议有效的情况下才支付下一次付款,我将只能看到上次付款的日期和下次付款的日期。< / p>
我正在使用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
...
我使用'min'作为下一个付款日期,假设有多个下一个付款日期。
答案 1 :(得分: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