当组状态= 0,1,2时总和为0,当它显示为0时总和为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
5 MESSI 1 1 1
6 DROGBA 1 1 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/935e78/4
我试图在每列中加上状态= 0,1,2:
SELECT
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,
p.policy_business_unit_id AS UNITS,
p.cia_ensure_id AS CIAS
FROM policies p
WHERE p.policy_business_unit_id IN ( 1 )
AND p.cia_ensure_id =1
GROUP BY p.state
结果如下:
STATE_0 STATE_1 STATE_2 UNITS CIAS
1 0 0 1 1
0 2 0 1 1
如何获得此结果?
STATE_0 STATE_1 STATE_2 UNITS CIAS
1 2 0 1 1
请相信我会得到各种帮助。 感谢。
答案 0 :(得分:1)
替换此
SELECT
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,
通过
SELECT
sum(CASE WHEN p.state =0 THEN 1 ELSE 0 end) AS state_0,
sum(CASE WHEN p.state =1 THEN 1 ELSE 0 END) AS state_1,
sum(CASE WHEN p.state =2 THEN 1 ELSE 0 END) AS state_2,
答案 1 :(得分:1)
如果您需要将state = 0或1或2的所有值组合在一起,那么您的查询必须略有不同。试试这个。
SELECT
SUM(CASE WHEN p.state = 0 THEN 1 ELSE 0 END) AS state_0,
SUM(CASE WHEN p.state = 1 THEN 1 ELSE 0 END) AS state_1,
SUM(CASE WHEN p.state = 2 THEN 1 ELSE 0 END) AS state_2,
p.policy_business_unit_id AS UNITS,
p.cia_ensure_id AS CIAS
FROM policies p
WHERE p.policy_business_unit_id IN ( 1 )
AND p.cia_ensure_id =1
GROUP BY CASE WHEN p.state IN (0,1,2) THEN 1 ELSE 0 END
这是一个有效的SQL FIDDLE,展示了它是如何运作的。
答案 2 :(得分:0)
您可能会考虑使用policy_business_unit_id和cia_ensure_id进行分组,因为您可能不仅要报告1和1,还要报告所有组合。
SELECT
sum(case when p.state = 0 then 1 else 0 end) AS state_0,
sum(case when p.state = 1 then 1 else 0 end) AS state_1,
sum(case when p.state = 2 then 1 else 0 end) AS state_2,
p.policy_business_unit_id AS UNITS,
p.cia_ensure_id AS CIAS
FROM policies p
--WHERE p.policy_business_unit_id IN ( 1 )
--AND p.cia_ensure_id =1
group by p.policy_business_unit_id, p.cia_ensure_id