按日期的销售报告的SQL查询

时间:2013-05-16 23:30:59

标签: sql postgresql pivot dynamic-pivot

我有一张销售线索表:

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

2 个答案:

答案 0 :(得分:1)

Pure SQL无法生成这样的结构(它是二维的,但是sql返回普通的记录列表)。

您可以像这样进行查询:

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

并通过报告系统对此数据进行视听。

答案 1 :(得分: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