SQL的两列值的值乘以日期范围
我需要回答的问题是“向名为“约翰·史密斯”的患者提供的吗啡的总成本是多少?”
在我的数据库架构中,我有以下模式:
Patient (patientNo, patName, patAddr, DOB)
Ward (wardNo, wardName, wardType, noOfBeds)
Contains (patientNo, wardNo, admissionDate)
Drug (drugNo, drugName, costPerUnit)
Prescribed (patientNo, drugNo, unitsPerDay, startDate, finishDate)
我已经为以上图案创建了一个示例模式: https://www.db-fiddle.com/f/wecc7cjtrykmerqpskmerqpskpsknr41/1
我如何构建查询以乘以costperunit*单位的乘以启动日期和终结者之间的天数,而无需手动计算几天?
目前我有:
SELECT SUM r.unitsPerDay*d.costPerUnit BETWEEN '2022-05-25' AND '2022-06-25' AS TotalCost, p.patName, d.drugName
FROM Prescribed r, Drug d, Patient p
WHERE p.patientNo=r.patientNo AND d.drugNo=r.drugNo AND r.drugNo=1001;
以下内容:
insert into Drug (drugNo, drugName, costPerUnit) values (1001, 'Morphine', '25.00');
insert into Patient (patientNo, patName, patAddr, DOB) values (101, 'John Smith', '123 Street', DATE '1990-01-01');
insert into Prescribed (patientNo, drugNo, unitsPerDay, startDate, finishDate) values (101, 1001, 4, DATE '2022-05-25', DATE '2022-06-25');
The question I need to answer is "What is the total cost of Morphine supplied to a patient called 'John Smith'?"
In my database schema I have the following schemas:
Patient (patientNo, patName, patAddr, DOB)
Ward (wardNo, wardName, wardType, noOfBeds)
Contains (patientNo, wardNo, admissionDate)
Drug (drugNo, drugName, costPerUnit)
Prescribed (patientNo, drugNo, unitsPerDay, startDate, finishDate)
I've created an example schema for the above here: https://www.db-fiddle.com/f/wecC7cjtryKMErqPskNr41/1
How would I structure the query to multiply costPerUnit*unitsPerDay by the amount of days between startDate and finishDate without manually counting the days?
Currently I have:
SELECT SUM r.unitsPerDay*d.costPerUnit BETWEEN '2022-05-25' AND '2022-06-25' AS TotalCost, p.patName, d.drugName
FROM Prescribed r, Drug d, Patient p
WHERE p.patientNo=r.patientNo AND d.drugNo=r.drugNo AND r.drugNo=1001;
from the following:
insert into Drug (drugNo, drugName, costPerUnit) values (1001, 'Morphine', '25.00');
insert into Patient (patientNo, patName, patAddr, DOB) values (101, 'John Smith', '123 Street', DATE '1990-01-01');
insert into Prescribed (patientNo, drugNo, unitsPerDay, startDate, finishDate) values (101, 1001, 4, DATE '2022-05-25', DATE '2022-06-25');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试此查询:
Try this query:
我已经更新了您的样本数据,以考虑到可以多次向同一患者开出相同的药物。
规定的吗啡的单位总数为
32*4 + 10*2 = 148
。 为25的费用应为并且按单位
I have updated your sample data to take into account that the same drug can be prescribed to the same patient multiple times.
The total number of units of Morphine prescribed would be
32*4 + 10*2 = 148
. And at the cost of 25 per unit the answer should be 3700.View on DB Fiddle