如何查找收据表中的每个客户的最后付款帐单

时间:2014-01-23 11:18:33

标签: winforms ms-access-2007 c#-2.0

表名:收据

列:
receipt_id,CUSTOMER_ID,receipt_date,receipt_amount

客户本可以支付很多账单。我想在收据表中找到每个客户的最后付款账单的详细信息。我使用嵌套查询,但我没有得到正确的结果。

select customer_id,receipt_date from receipt where receipt_id=(select top 1 receipt_id from receipt order by customer_id desc)

我使用Access 2007,C#2.0。

3 个答案:

答案 0 :(得分:1)

通过查找每个[customer_id]的最新[receipt_date]来获取每个客户的最新收据的详细信息

SELECT
    customer_id,
    MAX(receipt_date) AS max_receipt_date
FROM receipt
GROUP BY customer_id

然后,您可以将其用作查询中的一个组件,以返回该[customer_id]和日期的整个[收据]行:

SELECT receipt.*
FROM
    receipt
    INNER JOIN
    (
        SELECT
            customer_id,
            MAX(receipt_date) AS max_receipt_date
        FROM receipt
        GROUP BY customer_id
    ) AS max
        ON max.customer_id = receipt.customer_id
            AND max.max_receipt_date = receipt.receipt_date

答案 1 :(得分:1)

SELECT r1.*
FROM receipt r1
WHERE r1.recipt_date
    =
    (SELECT MAX(receipt_date) FROM receipt r2
         WHERE r2.customer_id = r1.customer_id
    );

此解决方案使用相关 - 子查询。

答案 2 :(得分:-1)

假设每次客户使用customer_id进行购买时都会插入记录,并且只有receipt_id不同......那么下面的SQL查询应该有效

选择receipt_id,receipt_date 从收据 group by customer_id;

你也可以通过receipt_date

添加订单