使用不同WHERE子句获取聚合的子查询

时间:2014-11-28 11:18:56

标签: sql postgresql aggregate-functions aggregate-filter

我正在执行此查询,我从Adwords报告中获取了一些数据:

SELECT "client_name", "customer_id",
  sum(clicks) as clicks,
  sum(impressions) as impressions,
  sum(cost) as cost,
  avg(avg_cpc) as avg_cpc,
  avg(conv_rate) as conv_rate,
  sum(total_conv_value) as total_conv_value,
  sum(converted_clicks) as converted_clicks,
  sum(conversions) as conversions,
  avg(search_impr_share) as search_impr_share,
  avg(cost_converted_click) as cost_converted_click,
  avg(average_position) as average_position
FROM "adwords_daily_account_performance"
WHERE "day" >= ?
GROUP BY "customer_id", "client_name"

该表还有一个名为network的列。此列可以是“展示广告网络”或“搜索网络”。此查询聚合来自两个网络的所有内容,但我想在查询中添加另一列以进行名为Ctr的聚合。

如何在Ctr列中将其汇总到同一查询中的网络=“搜索网络”的数据?

2 个答案:

答案 0 :(得分:3)

如果网络匹配,请使用case语句选择数字,否则输入0:

SELECT sum( CASE WHEN network = 'Search Network' THEN Ctr ELSE 0 END )

答案 1 :(得分:0)

在Postgres 9.4 + 中,您可以使用aggregate FILTER

sum(Ctr) FILTER (WHERE network = 'Search Network') AS sum_ctr

详细说明: