我有一个名为medics的表,名字第一名 和专业
具有名称和DOB两个表的表患者都具有id列主键。
还有另一个表访问,其中包含患者医生ID的ID
SELECT speciality, AVG (year(curdate()) - year(patients.DOB))
FROM medics, patients, visits
WHERE medics.IDM = visits.medics
GROUP by speciality;
我想做每个专业的平均年龄(我的意思是手术,儿科等)。选择查询有效但它向我显示每条线上所有患者的平均值相同。帮助我PLS!
答案 0 :(得分:0)
试一试:
SELECT
Speciality,
ROUND(AVG(YEAR(NOW())-YEAR(DOB)),0) AS Years
FROM visits
INNER JOIN medics
ON visits.IdMedic = medics.Id
INNER JOIN patients
ON visits.IdPatient = patients.Id
GROUP BY Speciality
我的桌子:
CREATE TABLE `visits` (
`Id` int(11) NOT NULL,
`IdMedic` int(11) DEFAULT NULL,
`IdPatient` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `patients` (
`Id` int(11) NOT NULL,
`Name` varchar(45) DEFAULT NULL,
`DOB` date DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `medics` (
`Id` int(11) NOT NULL,
`Name` varchar(45) DEFAULT NULL,
`Speciality` varchar(45) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;