选择分组依据并计算两列

时间:2017-11-24 03:34:09

标签: postgresql

我有这张桌子

+----+----------------------------+---------------+----------+
| ID |         CREATED_AT         |   CATEGORY    |   TYPE   |
+----+----------------------------+---------------+----------+
|  1 | 2017-11-23 23:00:40.221958 | SEM COBERTURA | callback |
|  2 | 2017-11-23 22:58:36.970052 | VENDA         | ativo    |
|  3 | 2017-11-23 22:47:03.956185 | SEM COBERTURA | ativo    |
|  4 | 2017-11-23 22:42:24.309915 | VENDA         | ativo    |
|  5 | 2017-11-23 22:32:48.780418 | SEM COBERTURA | callback |
|  6 | 2017-11-23 22:12:21.631433 | VENDA         | callback |
|  7 | 2017-11-23 22:09:38.52699  | SEM COBERTURA | ativo    |
|  8 | 2017-11-23 22:08:09.836343 | LIGACAO MUDA  | callback |
|  9 | 2017-11-23 22:08:07.058063 | SEM COBERTURA | callback |
| 10 | 2017-11-23 22:07:02.067439 | LIGACAO MUDA  | other    |
+----+----------------------------+---------------+----------+

根据上面的表格,我想要分组,并将列TYPE相加并对CATEGORY“VENDA”求和,例如:

这就是我想要的

+----------+------------+----------------+
|   TYPE   | COUNT_TYPE | COUNT_CATEGORY_VENDA |
+----------+------------+----------------+
| callback |          5 |              1 |
| ativo    |          4 |              2 |
| other    |          1 |              0 |
+----------+------------+----------------+

类型“回调”出现5次,有1个类别“VENDA”,“ativo”出现4次,有2个“VENDA”......

要获取TYPE和COUNT_TYPE我正在使用此查询:

SELECT TYPE, count(TYPE) AS COUNT_TYPE FROM table WHERE created_at BETWEEN '2017-11-23 00:00:00' AND '2017-11-23 23:59:00' GROUP BY TYPE ORDER BY COUNT_TYPE DESC

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。恕我直言,最简单的方法是使用case when来过滤查询中的内容。

SELECT
  TYPE,
  count(TYPE) AS COUNT_TYPE,
  SUM(
    case CATEGORY when 'VENDA' then 1 else 0 end
  ) AS COUNT_CATEGORY_VENDA
FROM table
WHERE
  created_at BETWEEN '2017-11-23 00:00:00' AND '2017-11-23 23:59:00' 
GROUP BY TYPE
ORDER BY COUNT_TYPE DESC;

除了CASE col WHEN d1 THEN v1 WHEN d2 THEN v2 ELSE v3 END,您还可以尝试CASE WHEN col = d1 THEN v1 WHEN col = d2 THEN v2 ELSE v3 END

另一种方法是使用子查询。

答案 1 :(得分:1)

你可以在postgresql中使用案例

SELECT TYPE, count(TYPE) AS COUNT_TYPE, SUM(case CATEGORY when 'VENDA' then 1 else 0 end) FROM table WHERE created_at BETWEEN '2017-11-23 00:00:00' AND '2017-11-23 23:59:00' GROUP BY TYPE ORDER BY COUNT_TYPE DESC