mysql sql选择每个组中的最后一条记录

时间:2016-04-06 15:41:19

标签: mysql sql select grouping

我有以下查询,在下面的屏幕截图中提供结果。我想要完成的是让最终结果只是每个invoice_number的最后一条记录。

我已经查看过有关按组或子组选择最后一条记录的其他问题,而且我的sql技能还没有达到我可以弄清楚如何应用那些提供的解决方案的水平其他问题。

感谢任何帮助。

SELECT 
    `Invoice`.Amount AS amount,
    zuora.convertDateTimeToGMTOffsetDateTime(`Invoice`.CreatedDate) AS created_date,
    `Invoice`.InvoiceNumber AS invoice_number,
    RatePlanCharge.chargeModel,
    RatePlanCharge.chargeType,
    `InvoiceItem`.`RatePlanChargeId`,
    CASE
        WHEN
            PaymentMethod.type = 'CreditCard'
        THEN
            CONCAT(PaymentMethod.creditCardType,
                    ' (',
                    REPLACE(PaymentMethod.creditCardMaskNumber,
                        '*',
                        ''),
                    ')')
        WHEN
            PaymentMethod.type = 'PayPal'
                AND PaymentMethod.paypalEmail != ''
        THEN
            IF(PaymentMethod.paypalEmail != '',
                CONCAT(PaymentMethod.type,
                        ' (',
                        PaymentMethod.paypalEmail,
                        ')'),
                PaymentMethod.type)
        WHEN PaymentMethod.type = 'WireTransfer' THEN 'Wire Transfer'
        ELSE IF(Invoice.Amount = 0,
            'None Required',
            IF(PaymentMethod.type,
                PaymentMethod.type,
                'Unpaid'))
    END AS payment_method,
    IF(RatePlanCharge.chargeModel != 'Discount'
            AND (RatePlanCharge.chargeType = 'Recurring'
            OR RatePlanCharge.chargeType = 'Usage'),
        TRUE,
        FALSE) AS recurring
FROM
    `InvoiceItem`
        JOIN
    `Invoice` ON `InvoiceItem`.`InvoiceId` = `Invoice`.`id`
        LEFT JOIN
    `RatePlanCharge` ON `RatePlanCharge`.`id` = `InvoiceItem`.`RatePlanChargeId`
        LEFT JOIN
    `InvoicePayment` ON `InvoicePayment`.`invoiceId` = `Invoice`.`id`
        LEFT JOIN
    `Payment` ON `Payment`.`id` = `InvoicePayment`.`paymentId`
        LEFT JOIN
    `PaymentMethod` ON `Payment`.`paymentMethodId` = `PaymentMethod`.`id`
        LEFT JOIN
    `CreditBalanceAdjustment` ON `CreditBalanceAdjustment`.`sourceTransactionId` = `Invoice`.`id`
WHERE
    `Invoice`.`Status` = 'Posted'
        AND Invoice.accountid = '2c92c0f84b786da2014bb934ef664f1b'

提供以下结果。我想将最终结果限制为以黄色突出显示的记录(每组发票号中的最后一条记录):

enter image description here

1 个答案:

答案 0 :(得分:0)

要获得每张发票的单行,您只需在查询结尾处添加 GROUP BY Invoice.InvoiceNumber
但是从你的帖子中不清楚'last'行的标准/属性是什么。它是orinal created_date属性(在屏幕截图中,已经转换的日期是无法区分的)?如果是这样,那么你应该首先按照invoce编号对结果集进行排序,然后按降序排序创建日期(这样每个发票的最新记录将列为第一个,组caluse将采用该结果),添加此
ORDER BY Invoice.InvoiceNumber asc, Invoice.CreatedDate desc GROUP BY Invoice.InvoiceNumber