2016-08-22 75 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