我需要获取n个不同发票编号的行。
我有SELECT查询,该查询为我提供了来自表的结果:
SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER
FROM TABLE1 AS A, TABLE2 AS B
WHERE A.INVOICE_NUMBER = B.INVOICE_NUMBER
AND A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
所以我的查询结果是这样的:
-----------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |
------------------------------------------------------
|1111111111-1 | 1 | P4324324525 |
-----------------------------------------------------
|1111111111-1 | 2 | P4565674574 |
-----------------------------------------------------
|1111111111-1 | 3 | V4324552557 |
-----------------------------------------------------
|1111111111-1 | 4 | V4324552525 |
-----------------------------------------------------
|2222222222-2 | 1 | S4563636574 |
-----------------------------------------------------
|3333333333-3 | 1 | Q4324325675 |
-----------------------------------------------------
|3333333333-3 | 2 | Q4565674574 |
-----------------------------------------------------
|4444444444-4 | 1 | F4326364366 |
-----------------------------------------------------
|4444444444-4 | 2 | F4565636323 |
-----------------------------------------------------
|4444444444-4 | 3 | F4398798588 |
-----------------------------------------------------
|4444444444-4 | 4 | F4565865888 |
-----------------------------------------------------
但是例如,我需要的是仅获取三个不同发票编号的结果,因此我的查询应给出以下内容:
-----------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |
------------------------------------------------------
|1111111111-1 | 1 | P4324324525 |
-----------------------------------------------------
|1111111111-1 | 2 | P4565674574 |
-----------------------------------------------------
|1111111111-1 | 3 | V4324552557 |
-----------------------------------------------------
|1111111111-1 | 4 | V4324552525 |
-----------------------------------------------------
|2222222222-2 | 1 | S4563636574 |
-----------------------------------------------------
|3333333333-3 | 1 | Q4324325675 |
-----------------------------------------------------
|3333333333-3 | 2 | Q4565674574 |
-----------------------------------------------------
我该如何实现?
答案 0 :(得分:2)
您听说过JOIN
吗?
无论如何,一种解决问题的方法是使用DENSE_RANK()
:
SELECT INVOICE_NUMBER, INVOICE_SEQ_NUMBER, FILE_NUMBER
FROM (SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER,
DENSE_RANK() OVER (ORDER BY A.INVOICE_NUMBER) as seqnum
FROM TABLE1 A JOIN
TABLE2 B
ON A.INVOICE_NUMBER = B.INVOICE_NUMBER AND
A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
) t
WHERE seqnum <= 3;