任务9 每个兽医每天开出的药物总费用是多少?仅显示兽医的ID,访问日期和总费用。按兽医的ID和访问日期对报告进行排序。
这是我得到的输出:
VET_ID VISIT_DATE TOTAL_COST
V01 21-Apr-2004 36.49
V01 21-Apr-2004 38.49
V01 21-Apr-2004 41.88
V01 21-Apr-2004 40.24
V01 21-Apr-2004 35.99
V01 21-Apr-2004 35.99
V01 27-Apr-2004 32.5
V01 27-Apr-2004 37.89
V01 27-Apr-2004 32
V01 27-Apr-2004 34.5
SELECT Visit.Vet_id, Visit.Visit_Date, (Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;
这是预期的输出:
Vet Date Total Cost
--- --------- ------------
V01 21-APR-04 12
V01 27-APR-04 16.25
V01 03-MAY-04 26.5
V01 22-JUN-04 30.39
V02 21-APR-04 38.5
V02 28-APR-04 12.5
V02 16-MAY-04 27.5
V03 28-APR-04 7.99
V03 08-MAY-04 7.99
V03 13-MAY-04 28.25
V04 03-MAY-04 10.49
V04 07-MAY-04 16.75
V04 12-MAY-04 46.05
V04 13-MAY-04 22.5
V04 17-MAY-04 32.85
V04 19-MAY-04 17.5
答案 0 :(得分:0)
您必须在加入后group by Visit.Vet_id, Visit.Visit_Date
才能计算总和:
SELECT
Visit.Vet_id,
Visit.Visit_Date,
SUM(Medication.Basic_Cost + Medication.Cost) AS Total_Cost
FROM Visit INNER JOIN Medication
ON Visit.Vet_id = Medication.Vet_id
GROUP BY Visit.Vet_id, Visit.Visit_Date
ORDER BY Visit.Vet_id, Visit.Visit_Date;
我猜Basic_Cost
和Cost
是表Medication
中的列,如果未更改为Visit
。
答案 1 :(得分:0)
您可以在自己的查询中使用子查询。听起来很像。
with grouped as (
SELECT
Visit.Vet_id,
Visit.Visit_Date,
(Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN
Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;
)
select
Vet_id,
Visit_Date,
sum(Total_Cost)
from grouped
group by
Vet_id,Visit_Date