两个同步的最大值

时间:2018-03-27 03:37:49

标签: sql oracle

我对数据库/查询等很陌生,所以如果我要问的问题非常基本,我很抱歉。

我有两张桌子:“收费”和“税收”。关闭第一个有两个要选择的字段:“invoiceNumber”和“sequentialInvoice”,后者有三个:“sequentialObligation”,“sequentialTax”和“reference”。

第一个表上的“invoiceNumber”=第二个表上的“reference”(用于匹配两个表)

我需要的是:对于所有存在重复“invoiceNumber”和“sequentialInvoice”的情况,只需获取最大的“sequentialObligation”及其相应的“sequentialTax”值。

我跑过的查询:

select CHA.invoiceNumber, CHA.sequentialInvoice, TAX.sequentialTax,max(TAX.sequentialObligation)  
from charging CHA, taxes TAX  
where CHA.CEMPTITU = 1 and CHA.invoiceNumber = TAX.reference and CHA.CEMPTITU = TAX.CEMPTITU  
group by CHA.invoiceNumber, CHA.sequentialInvoice, TAX.sequentialObligation, TAX.sequentialTax  
having count(CHA.invoiceNumber) >1  

查询返回

invoiceNumber sequentialInvoice sequentialTax max(tax.sequentalObligation)
441001970973         6537           12               3
441001970973         6537           16               2

等。 并且应该只返回第一行。我做错了什么?

PS:道歉,如果它太难看了;我发誓,我试图尽可能简单地解释它。

1 个答案:

答案 0 :(得分:0)

我们可以尝试在这里使用分析函数。在发票号和顺序发票上定义分区。然后,仅报告每个分区具有多个记录的记录,也具有最高的顺序义务值。

SELECT
    invoiceNumber,
    sequentialInvoice,
    sequentialTax,
    sequentialObligation
FROM
(
    SELECT
        CHA.invoiceNumber,
        CHA.sequentialInvoice,
        TAX.sequentialTax,
        TAX.sequentialObligation,
        COUNT(CHA.invoiceNumber) OVER (PARTITION BY CHA.invoiceNumber,
            CHA.sequentialInvoice) cnt,
        ROW_NUMBER() OVER (PARTITION BY CHA.invoiceNumber, CHA.sequentialInvoice
            ORDER BY TAX.sequentialObligation DESC) rn
    FROM charging CHA
    INNER JOIN taxes TAX
        ON CHA.invoiceNumber = TAX.reference AND
           CHA.CEMPTITU = TAX.CEMPTITU
    WHERE CHA.CEMPTITU = 1
) t
WHERE
    cnt > 1 AND rn = 1