on 12-29-2020 7:30 AM
Hi ,
I have a INVOICE_TABLE, in which we have 30 columns, in which one column named Document_type has distinct 6 values a doc_a, doc_b,.......doc_e & doc_f.
there are lakhs of records in total.
Now i have a requirement to fetch the recently created record for each document type so finally my query result should show all columns and has only 6 rows as we have 6 distinct document types
SELECT * FROM INVOICE_TABLE WHERE INVOICE_NUMBER IN
(
SELECT DISTINCT INVOICE_NUMBER FROM INVOICE_TABLE WHERE DOCUMENT_TYPE IN ('DOC_A','DOC_B','DOC_C','DOC_D','DOC_E','DOC_F')
GROUP BY DOCUMENT_TYPE,INVOICE_NUMBER,CREATION_DATE ORDER BY CREATION_DATE DESC,DOCUMENT_TYPE DESC LIMIT 6
)
Am using above query, but unfortunately it is fetching only 6 records and all 6 are doc_a type record.
Kindly do the need full.
One option is to use window function ROW_NUMBER like following. With that you get the latest data record (based on creation_date) per document type:
select * from (
select row_number() over (partition by document_type order by creation_date desc) as row_num, *
from INVOICE_TABLE
where document_type in ('DOC_A', 'DOC_B', 'DOC_C', 'DOC_D', 'DOC_E', 'DOC_F')
) where row_num = 1;
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
82 | |
11 | |
10 | |
8 | |
6 | |
6 | |
6 | |
6 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.