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
This would get you each one on a separate line:
SELECT
`cl`.`ndc`,
`cl`.`rx_num`
FROM `claims_list` AS `cl`
WHERE `cl`.`ndc` IN
(
SELECT `dl`.`ndc` FROM `drug_list` AS `dl`
WHERE `dl`.`type` = 'Generic'
ORDER BY `dl`.`qty` DESC
LIMIT 50
)
ORDER BY `cl`.`date` DESC
LIMIT 4
Then run the results through a filter in the calling script to group them together.
Making some assumptions, and I'm not sure the exact Oracle syntax....but what about:
SELECT
"ndc" as NDC,
( SELECT "rx_num" from "rx" WHERE "ndc"="drug_list"."ndc" ORDER BY "date" DESC LIMIT 1 OFFSET 0 ) as RX1,
( SELECT "rx_num" from "rx" WHERE "ndc"="drug_list"."ndc" ORDER BY "date" DESC LIMIT 1 OFFSET 1 ) as RX2,
( SELECT "rx_num" from "rx" WHERE "ndc"="drug_list"."ndc" ORDER BY "date" DESC LIMIT 1 OFFSET 2 ) as RX3,
( SELECT "rx_num" from "rx" WHERE "ndc"="drug_list"."ndc" ORDER BY "date" DESC LIMIT 1 OFFSET 3 ) as RX4
FROM "drug_list"
ORDER BY qty ASC
LIMIT 4
NDC | RX1 | RX2 | RX3 | RX4
123 2332 2342 2346 7776
You can use a combination of Analytics (if you are on a recent enough version of Oracle) and a Pivot Table to do it. This should work with your dataset.
select ndc,
max(decode(rn, 1, rx_num, null)) rx1,
max(decode(rn, 2, rx_num, null)) rx2,
max(decode(rn, 3, rx_num, null)) rx3,
max(decode(rn, 4, rx_num, null)) rx4
from (select *
from (select claims_list.ndc,
claims_list.rx_num,
row_number() over (partition by claims_list.ndc order by claims_list.date desc) rn
from claims_list,
(select *
from (select *
from drug_list
where type = 'Generic'
order by qty desc
)
where rownum < 51
) drug_list
where drug_list.ndc = claims_list.ndc
)
where rn < 5
order by ndc, rn
)
group by ndc;
The inner query uses analytics to pull the most recent 4 rx numbers for each drug based on the claim date. Then we use a pivot to take it from 4 lines per drug to one line with 4 columns.