Here is my situation:
I have one table that contains a list of drugs sold containing the NDC (an identifier), quantity sold, and whether the drug is a brand name or generic. I have another table that contains the prescription numbers, dates, and NDCs.
I need to generate a list of the most recent 4 prescription numbers for the top 50 generic drugs and the top 50 Brand name drugs.
Simplified example:
Drug_list:
NDC QTY Type
123 50 Generic
125 47 Brand
128 34 Generic
...
549 1 Brand
294 1 Generic
Claims_list:
NDC RX_num Date
123 1234 20081027
123 4194 20090517
594 12598 20091012
How would I write a join to generate a list of
NDC RX1, RX2, RX3, RX4
where NDC are the 50 most common 'Brand' NDCs, and the following RXs are the RX numbers of the most recent claims?
~~~~~~~
So far I've got this:
select t.ndc, cl.rx, cl.date from (
select * from (
select * from (
select * from drug_list where brand = 'Generic')
order by qty)
where rownum < 51) t
join claims_list cl on cl.ndc = t.ndc
order by t.ndc, cl.date;
Which gets me part of the way there. From there, how do I trim it down to only 4 results per NDC? And, is it possible to get it in the following from:
NDC, RX1, RX2, RX3, RX4
If I have to report it as:
NDC1, RX1
NDC1, RX2
NDC1, RX3
NDC1, RX4
NDC2, RX1
NDC2, RX2
NDC2, RX3
NDC2, RX4
NDC3, RX1
... etc
but I would prefer to have it on one line.
~~~~ (as requested by a comment: create table statements for example tables):
create table drug_list
(NDC varchar2(15), QTY number, type varchar2(10));
create table claims_list
(NDC varchar2(15), RX_num varchar2(20), "date" date);