1

我尝试了 Karwin 先生在这里提出的解决方案,
检索每组中的最后一条记录

我有一个单数表,其中包含我需要的所有记录以及 FF 记录。

 --------------------------------------------------
 | Keynum     | PaymentID  | BuyerID | LatestBill |
 |----------- | -----------|---------|------------|
 |   3        |    4       |    4    |  30000     |
 |   2        |    4       |    4    |  10000     |
 |   1        |    4       |    4    |  10000     |
 |   1        |    9       |    9    |  9999      |
 --------------------------------------------------

所需的输出是:

 --------------------------------------------------
 | Keynum     | PaymentID  | BuyerID | LatestBill |
 |----------- | -----------|---------|------------|
 |   3        |    4       |    4    |  30000     |
 |   1        |    9       |    9    |  9999      |
 --------------------------------------------------

我试过的是这样的:

  Select keynum, PaymentID, BuyerId, LatestBill From  Sales where LatestBill != 0 group by PaymentID, BuyerID order by keynum  Desc;

还有这个

 SELECT max(keynum), PaymentID, BuyerID, NewInstallmentBal
 FROM aliissales.tblmovedactual
 GROUP BY PaymentID, BuyerID DESC;

但是,我得到的是:

 --------------------------------------------------
 | Keynum     | PaymentID  | BuyerID | LatestBill |
 |----------- | -----------|---------|------------|
 |   1        |    4       |    4    |  10000     |
 |   1        |    9       |    9    |  9999      |
 --------------------------------------------------

我需要的是每组的最后一条记录,每条记录按 PaymentID 和 BuyerID 分组。

如果我使用 Max(keynum),它确实获得了每个组的最大 keynum,但不是相应的记录。是让记录与 Keynum 一起使用的更简单方法吗?

此外,如果 LatestBill = 0,则现在忽略整个组。

即如果

keynum 3 LatestBill = 0, group BuyerID 4 , PaymentID 4 is now ignored.    
4

2 回答 2

1
SELECT  a.*
FROM    aliissales.tblmovedactual a
        INNER JOIN
        (
            SELECT  max(keynum) xx, PaymentID, BuyerID
            FROM    aliissales.tblmovedactual
            GROUP   BY PaymentID, BuyerID
        ) b ON  a.PaymentID = b.PaymentID   AND
                a.BuyerID = b.BuyerID AND
                a.keynum = b.xx
于 2013-03-11T06:54:42.470 回答
0

SELECT keynum, PaymentID, BuyerID, NewInstallmentBal FROM aliissales.tblmovedactual WHERE keynum IN (SELECT max(keynum) FROM aliissales.tblmovedactual GROUP BY PaymentID)

于 2013-04-01T05:33:41.350 回答