MySQL从同一个字段中计算2个值

时间:2014-11-13 23:46:18

标签: mysql count

如何从同一个字段中计算两个不同的值?我有一个名为乔布斯的领域,我想在同一个查询中统计有多少医生和多少名警察。

这是我的查询,它同时计算两者但返回相同的结果。我想分开这个结果。这是我的疑问:

USE DBAssignmentPartC;
SELECT Cu_City as City, Count(Cu_Job) AS TotalPoliceDoctors FROM tblCustomers
WHERE Cu_Job = 'Doctor' OR Cu_Job = 'Policeman'
Group by Cu_City ORDER BY TotalPoliceDoctors DESC;

是否仍然可以统计医生和警察并将他们分别归还给他们?

我试过在这里和Google上搜索,但作为第一年的学生,我可能正在搜索/使用错误的条款,如果这已被回答并且我已经错过了,我道歉。

先谢谢

2 个答案:

答案 0 :(得分:2)

只需将Count(Cu_Job)更改为SUM(Cu_Job="Doctor") , SUM(cu_job ="Policeman")

即可
SELECT 
    Cu_City as City, 
    SUM(Cu_Job = "Doctor") as totalDoctors , 
    SUM(Cu_Job = "Policeman") AS totalPolice, 
    SUM(CASE WHEN Cu_Job = "Doctor" OR Cu_Job = "Policeman" THEN 1 ELSE 0 END) AS TotalPoliceDoctors 
FROM tblCustomers
GROUP BY Cu_City 
ORDER BY TotalPoliceDoctors DESC;

按城市返回每位医生的人数和每位警察的人数以及总人数

FIDDLE DEMO

注意: 只是让你知道这是如何工作的(所以你可以向你的教授解释它你需要)SUM(Cu_Job = "Doctor")返回一个布尔值意味着每一行Cu_Job = "Doctor"将为真或假。 MySQL(以及基本上所有其他编程语言)将true视为1,将false视为0.因此,总结'true'值将为您提供列中特定值的COUNT。

答案 1 :(得分:0)

试试这个。每个城市应该有两排,一个是警察,一个是医生,有计数

USE DBAssignmentPartC;
SELECT Cu_City as City, Count(Cu_Job) AS count FROM tblCustomers
WHERE Cu_Job = 'Doctor' OR Cu_Job = 'Policeman'
Group by Cu_City, Cu_Job ORDER BY count DESC;