我目前正在处理看起来像这样的SQL查询
SELECT reference.agent_ID, reference.policy_ID, Count(reference.status_ID) AS [Quoted Motor Breakdown] , Sum(IIf([status_ID]=1,1,0)) AS sold
FROM reference
GROUP BY reference.agent_ID, reference.policy_ID
HAVING (((reference.policy_ID)=1));
结果显示如下
Agent| Number of policies quoted for Motor breakdown|number of policies Motor breakdown sold
我想在同一个表中添加更多列,显示剩余策略类型的结果:
reference.policy_ID=2 (Travel),
reference.policy_ID=3 (Home Insurance) next to one agent
例如: 史密斯先生|引用汽车故障|出售|引用汽车旅行|出售
如果没有针对特定策略类型的引用,我还希望我的查询显示result = 0 任何建议将不胜感激 谢谢
答案 0 :(得分:1)
我认为你想要条件聚合:
SELECT r.agent_ID,
SUM(CASE WHEN r.policy_ID = 1 THEN 1 ELSE 0 END) AS [Quoted Motor Breakdown],
SUM(CASE WHEN r.policy_ID = 1 AND status_ID = 1 THEN 1 ELSE 0 END) AS sold,
SUM(CASE WHEN r.policy_ID = 2 THEN 1 ELSE 0 END) AS NumTravel,
SUM(CASE WHEN r.policy_ID = 3 THEN 1 ELSE 0 END) AS NumHomeInsurance
FROM reference r
GROUP BY r.agent_ID;
如果您使用的是MS Access,则需要使用非标准版iif()
:
SELECT r.agent_ID,
SUM(iif(r.policy_ID = 1, 1, 0)) AS [Quoted Motor Breakdown],
SUM(iif(r.policy_ID = 1 AND status_ID = 1, 1, 0)) AS sold,
SUM(iif(r.policy_ID = 2, 1, 0)) AS NumTravel,
SUM(iif(r.policy_ID = 3, 1, 0)) AS NumHomeInsurance
FROM reference as r
GROUP BY r.agent_ID;