1

我有一张销售线索表:

CREATE TABLE "lead" (
    "id" serial NOT NULL PRIMARY KEY,
    "marketer" varchar(500) NOT NULL,
    "date_set" varchar(500) NOT NULL
)
;
INSERT INTO lead VALUES (1, 'Joe', '05/01/13');
INSERT INTO lead VALUES (2, 'Joe', '05/02/13');
INSERT INTO lead VALUES (3, 'Joe', '05/03/13');
INSERT INTO lead VALUES (4, 'Sally', '05/03/13');
INSERT INTO lead VALUES (5, 'Sally', '05/03/13');
INSERT INTO lead VALUES (6, 'Andrew', '05/04/13');

我想生成一份报告,总结每个营销人员每天拥有的记录数。它应该如下所示:

| MARKETER | 05/01/13 | 05/02/13 | 05/03/13 | 05/04/13 |
--------------------------------------------------------
|      Joe |        1 |        1 |        1 |        0 |
|    Sally |        0 |        0 |        2 |        1 |
|   Andrew |        0 |        0 |        0 |        1 |

产生这个的 SQL 查询是什么?

我在 SQL Fiddle 上设置了这个示例:http ://sqlfiddle.com/#!12/eb27a/1

4

2 回答 2

1

纯 SQL 不能产生这样的结构(它是二维的,但 sql 返回普通的记录列表)。

你可以这样查询:

select marketer, date_set, count(id) 
from lead
group by marketer, date_set;

并通过您的报告系统将这些数据可视化。

于 2013-05-16T23:37:26.650 回答
1

你可以这样做:

select
  marketer,
  count(case when date_set = '05/01/13' then 1 else null end) as "05/01/13",
  count(case when date_set = '05/02/13' then 1 else null end) as "05/02/13",
  count(case when date_set = '05/03/13' then 1 else null end) as "05/03/13",
  count(case when date_set = '05/04/13' then 1 else null end) as "05/04/13"
from lead
group by marketer
于 2013-05-16T23:40:29.707 回答