我正在尝试计算 state = 0 和 state = 1 以及如果其他状态没有值则显示 0。
我的表:
|policies|
|id| |client| |policy_business_unit_id| |cia_ensure_id| |state|
1 MATT 1 1 0
2 STEVE 2 1 0
3 BILL 3 2 1
4 LARRY 4 2 1
|policy_business_units|
|id| |name| |comercial_area_id|
1 LIFE 2
2 ROB 1
3 SECURE 2
4 ACCIDENT 1
|comercial_areas|
|id| |name|
1 BANK
2 HOSPITAL
|cia_ensures|
|id| |name|
1 SPRINT
2 APPLE
信息如下:
http://sqlfiddle.com/#!2/54d2f/15
我正在尝试获取 states = 0,1,2 anc 计数,如果它不存在或显示 0
Select p.id, p.client,
pb.name as BUSINESS_UNITS,
ce.name as CIA,ca.name as COMERCIAL_AREAS,
count(p.state) as status_0,count(p.state) as status_1,count(p.state) as status_2
From policies p
INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id
INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id
INNER JOIN cia_ensures ce ON ce.id = p.cia_ensure_id
我得到这个结果:
ID CLIENT BUSINESS_UNITS CIA COMERCIAL_AREAS STATE_0 STATE_1 STATUS_2
1 MATT LIFE SPRINT HOSPITAL 4 4 4
我正在尝试计算 state = 0,1,2 否则在没有值的状态下显示 0
我该怎么做才能得到这个结果?
ID CLIENT BUSINESS_UNITS CIA COMERCIAL_AREAS STATE_0 STATE_1 STATE_2
1 MATT LIFE SPRINT HOSPITAL 1 0 0
2 STEVE ROB SPRINT BANK 1 0 0
3 BILL SECURE APPLE HOSPITAL 0 1 0
4 LARRY ACCIDENT APPLE BANK 0 1 0
拜托,我将不胜感激所有类型的帮助。 谢谢。
最佳答案
这应该可以解决问题。做一个 if 条件。如果 state = 0 然后计数 else 放入 0 查看工作 FIDDLE
SELECT
p.id,
p.client,
pb.name AS BUSINESS_UNITS,
ce.name AS CIA,ca.name AS COMERCIAL_AREAS,
IF (p.state = 0, count(p.state), 0) AS state_0,
IF (p.state = 1, count(p.state), 0) AS state_1,
IF (p.state = 2, count(p.state), 0) AS state_2
FROM policies p
INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id
INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id
INNER JOIN cia_ensures ce ON ce.id = p.cia_ensure_id
GROUP BY pb.id
ORDER BY p.id;
如果您想考虑空状态,这将是查询.. FIDDLE
SELECT
p.id,
p.client,
pb.name AS BUSINESS_UNITS,
ce.name AS CIA,ca.name AS COMERCIAL_AREAS,
IF (p.state = 0, count(p.state), 0) AS state_0,
IF (p.state = 1, count(p.state), 0) AS state_1,
IF (p.state IS NULL, count(p.id), 0) AS state_null
FROM policies p
INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id
INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id
INNER JOIN cia_ensures ce ON ce.id = p.cia_ensure_id
GROUP BY pb.id
ORDER BY p.id;
关于mysql - 如何根据条件对列进行计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815636/