模式:
test_record
-----------------------------------------------
|test_id | type_id | patient_no | medical_lab |
-----------------------------------------------
test_type
----------------------
|type_id | test_name |
----------------------
medical_lab
------------------------------
| lab_name | address | phone |
------------------------------注意: type_id是引用test_id的外键
我需要找到最受欢迎的医学实验室。最受欢迎的医学实验室是一个比任何其他医学实验室都能进行更多测试的实验室。
到目前为止,这就是我所拥有的:
SELECT medical_lab
FROM test_record, test_type
WHERE medical_lab = lab_name
AND test_record.type_id = test_type.type_id
GROUP BY type_id
HAVING COUNT(type_id) // not sure what to put here如你所见,我在计数部分被困住了。我基本上想要它,这样这个查询将只返回任何比其他同类医学实验室进行了更多测试的医学实验室。
示例:
lab example1 has conducted 10 tests of type 1
lab example2 has conducted 3 tests of type 1
lab example2 has conducted 2 tests of type 2
lab example3 has conducted 1 test of type 2然后,这个查询应该返回:
lab example1 // because it has done 10 tests of type 1
lab example2 // because it has conducted 2 tests of type 2发布于 2014-10-14 02:32:51
子查询将计算每个实验室为每个测试完成的测试数。
外部选择将选择每个测试具有最大测试计数的实验室。
SELECT T.lab_name, T.test_name, MAX(testcount)
FROM
(
SELECT M.lab_name, TT.test_name, COUNT(TT.test_name) as testCount
FROM medical_lab M
JOIN test_record TR
ON M.lab_name = TR.medical_lab
JOIN test_type TT
ON Tt.type_id = TR.type_id
GROUP BY M.lab_name, TT.test_name
) T
GROUP BY T.lab_name, T.test_namehttps://stackoverflow.com/questions/26351626
复制相似问题