在Select语句中执行减法,其中一个变量具有条件

时间:2017-01-05 12:58:30

标签: sql-server

我已经在下面进行了查询,现在想要修改它以获得“剩余条款”。

它应该以{{1​​}}的逻辑运行,这会带来术语总数减去已支付的术语。假设应该是今天的日期(运行查询的日期),其余的条件将是MAX(U_RowNo) - (MAX(U_RowNo),其中今天的日期小于或等于U_RowNo

查询

U_PaymentDate

[dbo]的样本结果。[@ LEASE_ROWS]

enter image description here

因此,如果某人在2017年7月21日运行报告,则SELECT DISTINCT T0.Code , T0.U_CardName , T0.U_MRADate , T0.U_RentalSchNo , T0.U_AssetDesc , T0.U_Currency , T0.U_AssetCost , T0.U_Tenure , T0.U_LRPayment , T0.U_PaymentTerms , T0.U_CommenceDate , T1.[Expiry Date] , T0.U_BankName AS 'Financier' , T2.[Remaining Terms] FROM [dbo].[@LEASE_HDR] T0 INNER JOIN ( SELECT U_DocNum , MAX(U_PaymentDate) AS 'Expiry Date' FROM [dbo].[@LEASE_ROWS] GROUP BY U_DocNum ) AS T1 ON T0.Code = T1.U_DocNum INNER JOIN ( SELECT U_DocNum , (MAX(U_RowNo) - X) AS 'Remaining Terms' FROM [dbo].[@LEASE_ROWS] GROUP BY U_DocNum ) AS T2 ON T0.Code = T2.U_DocNum INNER JOIN OCRD T3 ON T0.U_CardCode = T3.CardCode WHERE T0.U_Status = 'Contract' 的结果应为54 - 6 = 48。 ... 2017年7月22日 - > 54 - 6 = 48。 2017年7月23日 - > 54 - 7 = 47。

如何修改它?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,这可能就是你想要的。

SELECT DISTINCT T0.Code
    , T0.U_CardName
    , T0.U_MRADate
    , T0.U_RentalSchNo
    , T0.U_AssetDesc
    , T0.U_Currency
    , T0.U_AssetCost
    , T0.U_Tenure
    , T0.U_LRPayment
    , T0.U_PaymentTerms
    , T0.U_CommenceDate
    , T1.[Expiry Date]
    , T0.U_BankName AS "Financier"
    , T2.RT1 - COALESCE(T4.RT1,0) AS "Remaining Terms"
FROM [dbo].[@LEASE_HDR] T0
INNER JOIN (
    SELECT U_DocNum
        , MAX(U_PaymentDate) AS 'Expiry Date'
    FROM [dbo].[@LEASE_ROWS]
    GROUP BY U_DocNum
    ) AS T1
    ON T0.Code = T1.U_DocNum
INNER JOIN (
    SELECT U_DocNum
        , MAX(U_RowNo) AS RT1
    FROM [dbo].[@LEASE_ROWS]
    GROUP BY U_DocNum
    ) AS T2
    ON T0.Code = T2.U_DocNum
LEFT JOIN (
    SELECT U_DocNum
        , MAX(U_RowNo) AS 'RT2'
    FROM [dbo].[@LEASE_ROWS]
    WHERE U_PaymentDate <= GETDATE()
    GROUP BY U_DocNum
    )   AS T4
    ON T0.Code = T4.U_DocNum
INNER JOIN OCRD T3
    ON T0.U_CardCode = T3.CardCode
WHERE T0.U_Status = 'Contract'