我正在尝试根据我的销售表打印报告,但很难写出我的查询。
+----------+--------+-----------+-------+------------+
| SALES |
+----------+--------+-----------+-------+------------+
| agent_id | type | result | value | date |
+----------+--------+-----------+-------+------------+
| 1 | sales | yes | 12.34 | 2018-05-01 |
| 1 | sales | yes | 5.45 | 2018-05-01 |
| 1 | return | other | 7.00 | 2018-05-01 |
| 1 | return | saved | 19.99 | 2018-05-01 |
| 1 | return | not_saved | 1.19 | 2018-05-01 |
| 2 | return | saved | 1.34 | 2018-05-01 |
| 2 | return | not_saved | 29.04 | 2018-05-01 |
| 2 | sales | yes | 11.11 | 2018-05-01 |
| 3 | sales | no | 10.00 | 2018-05-01 |
| 3 | sales | no | 89.34 | 2018-05-01 |
| 3 | sales | yes | 1.41 | 2018-05-01 |
| 3 | sales | other | 2.41 | 2018-05-01 |
| 3 | sales | other | 2.41 | 2018-04-28 |
+----------+--------+-----------+-------+------------+
我在下面的查询中第3,第4和第5列遇到了困难。
COLUMN1 = agent_id
COLUMN2 =通话次数。 这是每个代理的记录数
COLUMN3 =保存数量。
这将记录type
为'销售'并且result
为'是'的记录
COLUMN4 =保存的值。
这是总和(值),其中type
=“销售”和result
=“是”
COLUMN5 =转换率。 这将是(column3 / column2)x100
这个查询是我能得到的。我无法弄清楚剩下的。任何人都可以指导我朝正确的方向发展吗?
SELECT agent_id,count(*) AS 'Number of Calls',COLUMN3,COLUMN4,COLUMN5
FROM sales
WHERE comm_ts > '2018-04-29'
GROUP BY agent_id;
这将是我的结果集
+----------+--------+----------+-------+------------+---------+------------+
| agent_id | Number of Calls | COLUMN3 | COLUMN4 | COLUMN5 |
+----------+--------+-----------+-------------------+---------+------------+
| 1 | 5 | 2 | 17.79 | 40% |
| 2 | 3 | 1 | 11.11 | 33% |
| 3 | 4 | 1 | 1.41 | 25% |
+----------+--------+----------+--------------------+---------+------------+
答案 0 :(得分:1)
我认为你想要条件聚合:
SELECT agent_id, count(*) AS num_calls,
sum(case when type = 'sales' and result = 'yes' then 1 else 0 end) as column3,
sum(case when type = 'sales' and result = 'yes' then value else 0 end) as column4,
avg(case when type = 'sales' and result = 'yes' then 1.0 else 0 end) as column5
FROM sales
WHERE comm_ts > '2018-04-29'
GROUP BY agent_id;