2016-08-22 80 views
2

我想显示更大金额的Posting键(我用MAX命令来获得)。如何显示更大的金额

在附加的图片上,我需要将相同的值与同一个值进行分组,同时将较高的金额减去较小的金额,但这里的冲突是我需要显示更高金额的posting_key。

POSTING_KEY

SELECT PUBLICATION_CODE, 
    RS_GL_ACCT_NO, 
    ASSIGNMENT, 
    TEXT, 
    RRAC_TYPE, 
    MAX(INV_TAX_AMT)-MIN(INV_TAX_AMT) AS INV_TAX_AMT, 
    RS_AMOUNT, 
    POSTING_KEY 
FROM SAP_TABLE 
GROUP BY PUBLICATION_CODE, 
    RS_GL_ACCT_NO, 
    ASSIGNMENT, 
    TEXT, 
    RRAC_TYPE, 
    RS_AMOUNT, 
    POSTING_KEY; 
+0

简单的查询就可以了,并把它写在SP是没有必要的。 – user3664645

回答

1

试试这个:

select 
    a.PUBLICATION_CODE, 
    a.RS_GL_ACCT_NO, 
    a.TEXT, 
    a.RRAC_TYPE, 
    a.INV_TAX_AMT-b.INV_TAX_AMT AS INV_TAX_AMT, 
    a.RS_AMOUNT, 
    c.POSTING_KEY 
from sap_Table a 
join sap_Table b on (a.RS_GL_ACCT_NO = b.RS_GL_ACCT_NO and b.INV_TAX_AMT < a.INV_TAX_AMT) 
join (select RS_GL_ACCT_NO, max(posting_key) as posting_key from sap_Table) c on (a.RS_GL_ACCT_NO = b.RS_GL_ACCT_NO) 

让我知道,如果有什么失败:)

1

您可以使用分析功能row_number()min()max()

select p_code, gl_code, text, type, tax_amt, invoice_amt, posting_key 
    from (
    select row_number() over (partition by p_code, gl_code order by tax_amt desc) as rn, 
      max(tax_amt) over (partition by p_code, gl_code) 
      - min(tax_amt) over (partition by p_code, gl_code) as tax_amt, 
      p_code, gl_code, text, type, invoice_amt, posting_key 
     from sap_table) 
    where rn = 1 

测试数据和输出:

create table sap_table (p_code varchar2(2), gl_code number(6), text varchar2(25), 
    type varchar2(20), tax_amt number(8, 2), invoice_amt number(6), posting_key number(6)); 
insert into sap_table values ('LH', 160069, 'Prepaid Charge-Out 0916', 
           'Tax For Charge', .96, 0, 53); 
insert into sap_table values ('LH', 160069, 'Prepaid Charge-Out 0916', 
           'Tax For Charge', .5, 0, 54); 

P_CODE GL_CODE TEXT      TYPE    TAX_AMT INVOICE_AMT POSTING_KEY 
------ ------- ------------------------- --------------- ---------- ----------- ----------- 
LH  160069 Prepaid Charge-Out 0916 Tax For Charge  0,46   0   53