按组ID查看mysql顺序的最新存储值'小号

时间:2015-08-09 11:27:21

标签: php mysql

您的查询仅执行此操作不正确请参阅下面的另一个示例

pid  customer id  invoice id     name  due amount make payment

 1      1001           086    sasi      36       sasi      10 
 5     1003            084    ram       100      ram       50
 7     1002            083    koushil   80       am         50

查询是

SELECT * FROM print_reciept pr     内部联接     (         SELECT invoice_id,MIN(pid)AS min_pid         FROM print_reciept         WHERE due_amount!= 0         GROUP BY invoice_id     )t ON pr.invoice_id = t.invoice_id AND pr.pid = t.min_pid WHERE due_amount!= 0;

再看一遍这个例子

pid  customer id  invoice id  name  due amount make_pay paid_amount

1      1001           086    sasi      36       sasi      10   
2      1001           086    sasi      26       ram        5
3      1001           086    sasi      21       ravi      10 
4      1001           086    sasi      11       sasi      10     
5     1003            084    ram       100      ram       50
6     1003            084    raghu     50       sasi      10 
7     1002            083    koushil   80       am         50
8      1002           083     koushil  30        am        20 

这是我的结果,但我已经在相同的ID使用发票ID 086

中支付到期6

我需要结果

pid  customer id  invoice id     name  due amount make payment

 4      1001           086       sasi         11       sasi      10
 6     1003            084      raghu         50       sasi      10 
 8      1002           083     koushil        30        am       20 

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确。

如果您想获得invoice_id = 086的最后一个值:

SELECT pid, cust_id, cust_name, date, invoice_id, invoice_date, 
  invoice_amount, paid_amount, paymentmade, makeapayment, due_amount, status
FROM print_reciept
WHERE invoice_id = 086
  AND due_amount != 0
ORDER BY pid DESC
LIMIT 1;

如果您想获取每个invoice_id的最后一个值:

SELECT *
FROM print_reciept pr
    INNER JOIN
    (
        SELECT invoice_id, MIN(pid) AS min_pid
        FROM print_reciept
        WHERE due_amount != 0
        GROUP BY invoice_id
    ) t ON pr.invoice_id = t.invoice_id AND pr.pid = t.min_pid
WHERE due_amount != 0;

答案 1 :(得分:0)

SELECT *
FROM print_reciept pr
    INNER JOIN
    (
        SELECT invoice_id, MAX(pid) AS min_pid
        FROM print_reciept
        WHERE due_amount != 0
        GROUP BY invoice_id
    ) t ON pr.invoice_id = t.invoice_id AND pr.pid = t.min_pid
WHERE due_amount != 0;