基于条件的sql自定义返回值

bakd9h0s  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(338)

我是sql server的新手,请您帮助我进行以下查询查询:我有下表-表1:-

PostingDate     ReturnCheckReason           PaymentStatus   PolicyNumber
7/23/2020 15:30 Cancel Payment                  Return          1234
8/6/2020 17:40  Cancel Payment                  Return          1234

在这里我将显示返回响应,这是定制的响应

PostingDate     ReturnCheckReason           PaymentStatus           PolicyNumber
null                Cancel Payment      ALL Payments are Canceled           1234

这是我的query:-

SELECT TOP 1
    [PolicyNumber],
    [PostingDate],
    [PaymentStatus]
    FROM [dbo].[Bil_PaymentSearch] WITH (NOLOCK)
    WHERE 
         (PolicyNumber = @PolicyNumber) AND
          (REturnCheckreason <> 'Cancel payment') AND 
         (PaymentOrReturn <> 'Return')
    ORDER BY PostingDate ASC

如果表数据如下所示:-

PostingDate     ReturnCheckReason   PaymentStatus   PolicyNumber
7/23/2020 15:30 Null                    Payment         1234
8/6/2020 17:40  Null                    Payment         1234
8/4/2020 14:29  Null                    Payment         1234
8/5/2020 6:09   Null                    Payment         1234
8/5/2020 12:47  Cancel Payment          Return          1234

然后我需要返回如果第一次付款没有取消,我需要返回该行。所以我写了这个查询-

SELECT TOP 1
    [PolicyNumber],
    [PostingDate],
    [PaymentStatus]
    FROM [dbo].[Bil_PaymentSearch] WITH (NOLOCK)
    WHERE 
         (PolicyNumber = @PolicyNumber) AND
          (REturnCheckreason <> 'Cancel payment') AND 
         (PaymentOrReturn <> 'Return')
    ORDER BY PostingDate ASC

所以现在我需要结合你的查询和我的查询来处理以下两种情况,你能帮我吗
如果第一笔付款没有取消,我需要退回那一行。
如果如上所示取消了该策略的所有支付,那么我们需要显示自定义消息,否则我的查询将显示null

mrwjdhj3

mrwjdhj31#

可以使用聚合和条件逻辑:

SELECT PolicyNumber, MAX(ReturnCheckReason), 
       (CASE WHEN MIN(ReturnCheckReason) = MAX(ReturnCheckReason) AND MAX(ReturnCheckReason) = 'Cancel payment'
             THEN 'All Payments Cancelled'
         END)
FROM [dbo].[Bil_PaymentSearch] bps
WHERE PolicyNumber = @PolicyNumber 
GROUP BY PolicyNumber

相关问题