我有一个SQL查询,并想知道如何实现一个总和来计算平均值。
我创建了此查询以输出以下图片:
SELECT d.date, CONCAT_WS(' ', p.PatientFname ,p.PatientLname) AS "Patient", dc.drugcost_cost, pc.pharmacy_name FROM drugcost dc JOIN patients_copy p ON dc.Patients_copy_idPatients = p.idPatients LEFT JOIN time d ON dc.time_idtime = d.idtime LEFT JOIN pharmacy_location pc ON dc.pharmacy_location_idpharmacy = pc.idpharmacy ORDER BY Patient ASC
我想扩展查询以获取新列或新查询中同一患者的每年平均值。
这可能吗?我希望你明白我想要的东西。
由于
答案 0 :(得分:1)
SELECT EXTRACT(YEAR FROM date) AS "Year",
CONCAT_WS(' ', p.PatientFname ,p.PatientLname) AS "Patient",
AVG(dc.drugcost_cost) AS "AvgCost"
FROM drugcost dc
JOIN patients_copy p ON dc.Patients_copy_idPatients = p.idPatients
LEFT JOIN time d ON dc.time_idtime = d.idtime
LEFT JOIN pharmacy_location pc ON dc.pharmacy_location_idpharmacy = pc.idpharmacy
GROUP BY EXTRACT(YEAR FROM date),
ONCAT_WS(' ', p.PatientFname ,p.PatientLname)
将pc.pharmacy_name添加到结果中:
SELECT EXTRACT(YEAR FROM date) AS "Year",
CONCAT_WS(' ', p.PatientFname ,p.PatientLname) AS "Patient",
AVG(dc.drugcost_cost) AS "AvgCost",
pc.pharmacy_name
FROM drugcost dc
JOIN patients_copy p ON dc.Patients_copy_idPatients = p.idPatients
LEFT JOIN time d ON dc.time_idtime = d.idtime
LEFT JOIN pharmacy_location pc ON dc.pharmacy_location_idpharmacy = pc.idpharmacy
GROUP BY EXTRACT(YEAR FROM date),
ONCAT_WS(' ', p.PatientFname ,p.PatientLname),
pc.pharmacy_name
答案 1 :(得分:0)
AVG()
SQL函数可以帮助你
SELECT d.date, CONCAT_WS(' ', p.PatientFname ,p.PatientLname) AS "Patient",
AVG(dc.drugcost_cost) AS "Average", pc.pharmacy_name
FROM drugcost dc
JOIN patients_copy p
ON dc.Patients_copy_idPatients = p.idPatients
LEFT JOIN time d
ON dc.time_idtime = d.idtime
LEFT JOIN pharmacy_location pc
ON dc.pharmacy_location_idpharmacy = pc.idpharmacy
ORDER BY Patient ASC
SELECT d.date, CONCAT_WS(' ', p.PatientFname ,p.PatientLname) AS "Patient",
AVG(dc.drugcost_cost) AS "Average", pc.pharmacy_name
FROM drugcost dc
JOIN patients_copy p
ON dc.Patients_copy_idPatients = p.idPatients
LEFT JOIN time d
ON dc.time_idtime = d.idtime
LEFT JOIN pharmacy_location pc
ON dc.pharmacy_location_idpharmacy = pc.idpharmacy
GROUP BY "Patient"
ORDER BY Patient ASC