1

很确定我的问题标题很糟糕,但无论如何我有一个名为 invoices 的表格,在该表格内每个发票都有一个 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
4

3 回答 3

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
于 2012-08-29T04:16:41.447 回答
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 

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

于 2012-08-29T04:23:58.740 回答
0

在您的子选择中按 i.id DESC 排序

于 2012-08-29T04:17:57.750 回答