通过GROUPIM语句中的另一列的MAXIMUM选择记录并通过二进制变量选择另一条记录-SQL Server

时间:2019-05-21 03:40:33

标签: sql sql-server

我正在尝试根据付款的最大值和比率(基于SQL Server中称为Rate_Include的指示变量)检索帐户的主要付款说明。由于我是SQL Server的新手,所以我想知道是否有人可以帮助我进行此查询。我尝试使用具有和内部联接,但是这个问题要复杂一些。

这是用于SSMS Studio 17的。该表称为Payment

原始表如下所示。

Payment

预期输出:

Aggregated Results

2 个答案:

答案 0 :(得分:0)

以下查询将很有帮助。

SELECT ACCOUNT_NUMBER, SUM(Payment_Amount)  Payment_Amount, '' Dominant_Payment, 0.00 
Rate, MAX(Payment_Amount) MaxPayment
INTO #PAYMENTS
FROM Payments
GROUP BY ACCOUNT_NUMBER

--Updating Dominant_Payment
UPDATE TP  SET Dominant_Payment = P.Payment_Description
FROM Payments P 
JOIN #PAYMENTS TP ON P.ACCOUNT_NUMBER = TP.ACCOUNT_NUMBER AND P.Payment_Amount = 
TP.MaxPayment
--Updating Rate
UPDATE TP  SET Rate = P.Rate
FROM Payments P 
JOIN #PAYMENTS TP ON P.ACCOUNT_NUMBER = TP.ACCOUNT_NUMBER AND P.Rate_Include = 'Y'

SELECT ACCOUNT_NUMBER, Payment_Amount, Dominant_Payment, Rate
FROM #PAYMENTS

DROP TABLE #PAYMENTS

答案 1 :(得分:0)

有很多方法可以完成此任务。出于可读性目的,子查询非常易于理解。我已经为你分手了。

请注意,这是非常快速的内容,尚未进行优化。我建议您进一步研究JOINS和子查询,并尝试其他方法。

            SELECT p.Account_Number,
                   SUM(p.Payment_Amount) AS Payment_Amount,
                   sub2.Payment_Description,
                   sub3.Rate
            FROM Payment p

            JOIN (SELECT Account_Number,
                              MAX(Payment_Amount) AS Payment_Amount
                       FROM Payment
                       GROUP BY Account_Number) sub ON p.Account_Number = sub.Account_Number

            JOIN (SELECT Account_Number,
                              Payment_Amount,
                              Payment_Description
                       FROM Payment) sub2 ON sub.Account_Number = sub2.Account_Number AND sub.Payment_Amount = sub2.Payment_Amount

            JOIN (SELECT Account_Number,
                              MAX(Rate) AS Rate
                       FROM Payment WHERE Rate_Included = 'Y'
                       GROUP BY Account_Number) sub3 ON sub.Account_Number = sub3.Account_Number

            GROUP BY p.Account_Number,
                     Sub2.Payment_Description,
                     sub3.Rate