Question

I have a table of sales leads:

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');

I want to produce a report that summarizes the number of records each marketer has for each day. It should look like this:

| 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 |

What's the SQL query to produce this?

I have this example set up on SQL Fiddle: http://sqlfiddle.com/#!12/eb27a/1

Was it helpful?

Solution

Pure SQL cannot produce such structure (it is two dimensional, but sql return plain list of records).

You could make query like this:

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

And vizualise this data by your reporting system.

OTHER TIPS

You can do it like this:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top