3

我正在使用 SQL Server。我使用了这段代码:

 select distinct A.CustomerNo, A.INV_Nr, B.Code, A.Price 
 from INVOICE A.
      INVOICE_LINE B
 where
      A.IVC_Nr = B.IVC_Nr

输出是这样的:

| CustomerNo   |    INV_Nr   |   Code   | Price |
=================================================
| 1100021      |    500897   |   1404   | 2500  |
| 1100021      |    500897   |   1403   | 2500  |
| 1100022      |    500898   |   1405   | 3500  |
| 1100023      |    500899   |   1405   | 3000  |
| 1100023      |    500899   |   1403   | 3000  |

如何删除第二行并仅获取相同数字的第一行,应该是这样的:

| CustomerNo   |    INV_Nr   |   Code   | Price |
=================================================
| 1100021      |    500897   |   1404   | 2500  |
| 1100022      |    500898   |   1405   | 3500  |
| 1100023      |    500899   |   1405   | 3000  |

谢谢,

4

1 回答 1

6

由于问题是用 标记SQL Server 2005+,因此您可以使用Common Table Expressionand Window Function

WITH recordsList
AS
(
    SELECT  A.CustomerNo, A.INV_Nr, B.Code, A.Price ,
            ROW_NUMBER() OVER (PARTITION BY A.CustomerNo
                                ORDER BY B.Code DESC) rn
    FROM    INVOICE A
            INNER JOIN INVOICE_LINE B
                ON A.IVC_Nr = B.IVC_Nr
)
SELECT  CustomerNo, INV_Nr, Code, Price
FROM    recordsList
WHERE   rn = 1
于 2013-01-26T08:16:00.237 回答