SQL获取最新记录

时间:2012-08-29 04:11:49

标签: sql select

非常确定我的问题标题很糟糕,但无论如何我有一张名为发票的表,在该表内,每张发票都有一个ID,每个id都有一个客户端ID,因此客户将有多张发票。我试图获得最新的发票余额,我写的代码不起作用,谁能告诉我我做错了什么?

SELECT c.clientid,
    c.clientname,
    c.billingdate,
    (SELECT remainingbalance 
     FROM invoice i 
     WHERE i.client = c.clientid) AS remaining
FROM client c
ORDER BY clientname

3 个答案:

答案 0 :(得分:5)

使用INNER JOIN

试试这个

更新: 我修改了我的答案,看看是否有效

 SELECT c.clientid,
 c.clientname,
 c.billingdate,
 d.remainingbalance
 FROM client c 
 INNER JOIN (
             SELECT  clientid,
             MAX(invoiceid) invoiceid
             FROM    invoice
             GROUP BY  clientid
             ) d
 ON c.clientid = d.clientid
 ORDER BY c.clientname

答案 1 :(得分:3)

离开球,试试

之类的东西
SELECT  c.clientid, 
        c.clientname, 
        c.billingdate, 
        (
            SELECT  TOP 1 
                    remainingbalance  
            FROM    invoice i  
            WHERE   i.client = c.clientid
            ORDER BY i.invoiceid DESC
        ) AS remaining 
FROM    client c 
ORDER BY    clientname

您使用的是哪个RDMS?

另一种方法如下

SELECT  c.clientid,  
        c.clientname,  
        c.billingdate,
        rb.remainingbalance
FROM    client c  INNER JOIN
        (
            SELECT  i.clientid,
                    i.remainingbalance 
            FROM    invoice i INNER JOIN
                    (
                        SELECT  clientid,
                                MAX(invoiceid) invoiceid
                        FROM    invoice
                        GROUP BY    clientid
                    ) m ON  i.invoiceid = m.invoiceid
                        AND i.clientid = m.clientid
        ) rb    ON  c.clientid = rb.clientid
ORDER BY clientname 

首先获得每个客户的“最新”发票,然后从该发票中获取所需的详细信息并显示客户信息。

答案 2 :(得分:0)

通过i.id DESC在您的子选择中订购