通常,我对SQL查询非常有信心,但是这让我抓狂了。我觉得这样-应该-快速修复,但是我只是没有看到它。
我正在尝试在一个查询中对同一表上的多个值进行计数。
不要介意“0000000000000000”,它只是表示一个空字节数组。
有没有简单的方法来组合这些查询?
SELECT COUNT(ssn)
FROM patients
WHERE ssn="0000000000000000";
SELECT COUNT(firstname)
FROM patients
WHERE firstname="0000000000000000"
SELECT COUNT(lastname)
FROM patients
WHERE lastname="0000000000000000"
etc...
最佳答案
你可以做这样的事情-
SELECT COUNT(ssn) AS patient_count, 'ssn' AS count_type
FROM patients
WHERE ssn="0000000000000000";
UNION
SELECT COUNT(firstname) AS patient_count, 'firstname' AS count_type
FROM patients
WHERE firstname="0000000000000000"
UNION
SELECT COUNT(lastname) AS patient_count, 'lastname' AS count_type
FROM patients
WHERE lastname="0000000000000000"