以下是我的情况:
我有一张表,其中包含销售的药品清单,其中包含NDC(标识符),销售数量以及药品是品牌名称还是通用名称。我有另一张表,其中包含处方号,日期和NDC。
我需要生成前50种仿制药和前50种品牌药的最新4种处方号列表。
简化示例:
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
如何编写联接以生成
列表NDC RX1, RX2, RX3, RX4
NDC是50个最常见的“品牌”NDC,以下RX是最近声明的RX号码?
~~~~~~~
到目前为止,我已经得到了这个:
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;
这让我成为那里的一部分。从那里开始,我如何将其减少到每个NDC只有4个结果?而且,是否有可能从以下方面得到它:
NDC, RX1, RX2, RX3, RX4
如果我必须将其报告为:
NDC1, RX1
NDC1, RX2
NDC1, RX3
NDC1, RX4
NDC2, RX1
NDC2, RX2
NDC2, RX3
NDC2, RX4
NDC3, RX1
... etc
但我更愿意将它放在一条线上。
~~~~ (根据注释的要求:为表格表创建表语句):
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);
答案 0 :(得分:1)
您可以结合使用Google Analytics(如果您使用的是最新的Oracle版本)和数据透视表来完成此操作。这应该适用于您的数据集。
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;
内部查询使用分析根据声明日期提取每种药物的最新4个rx数字。然后我们使用一个转轴将它从每个药物的4行带到4行的一行。
答案 1 :(得分:0)
做出一些假设,我不确定确切的Oracle语法......但是呢:
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
答案 2 :(得分:0)
这会让你们每个人都分开来一行:
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
然后通过调用脚本中的过滤器运行结果,将它们组合在一起。