时间:2017-01-30 16:16:08

标签: sql postgresql group-by case

我甚至不知道我在技术上要求什么,所以一直在努力寻找答案。我有这个查询在MySQL工作,但切换到PostgreSQL有点挑战。

SELECT call.call_id,
    SUM(CASE WHEN indicator.indicator_name = 'Appointment Set' THEN indicator_score.score_value  ELSE '0' END) as "Appointment Set" ,
    SUM(CASE WHEN indicator.indicator_name = 'Ask for Business' THEN indicator_score.score_value  ELSE '0'  END) as "Ask for Business"
FROM call
JOIN indicator_score ON indicator_score.call_id = call.call_id
JOIN indicator ON indicator.indicator_id = indicator_score.indicator_id
JOIN org_unit ON org_unit.org_unit_id = call.org_unit_id
WHERE call.org_unit_id IN (4147, 4153)
group by call.call_id, indicator_name

每个call_id可以而且应该有“Ask for Business”和“Appointment Set”的分数,但我得到的是一个有分数而另一个有'0'。

call_id   | Appointment Set | Ask for Business
--------------------------------------------
3,001,144 |         0       |         89
3,001,145 |       100       |          0

我正在寻找的是这样的:

call_id   | Appointment Set | Ask for Business
--------------------------------------------
3,001,144 |      100        |         89

我也试过这个结构,但是我得到了相同的结果。

SELECT call.call_id,
CASE indicator.indicator_name WHEN 'Appointment Set' THEN sum(indicator_score.score_value)  ELSE '0'  END as Appointment_Set ,
CASE indicator.indicator_name WHEN 'Ask for Business' THEN sum(indicator_score.score_value)  ELSE '0'  END as Ask_for_Business
FROM call
JOIN indicator_score ON indicator_score.call_id = call.call_id
JOIN indicator ON indicator.indicator_id = indicator_score.indicator_id
JOIN org_unit ON org_unit.org_unit_id = call.org_unit_id
WHERE call.org_unit_id IN (4147, 4153)
group by call.call_id, indicator_name

1 个答案:

答案 0 :(得分:3)

使用

group by call.call_id, indicator_name

你当然只有一个call_id行,一行用于indicator_name ='约会集'一个用于indicator_name ='要求商业& #39;

如果您只需要每call_id行一行,那么只能按call_id分组:

group by call.call_id