5

Here is the dummy data, it's a calls record data table.

This is a glimpse of it:

|  call_id  |   customer   |   company   |     call_start      | 
|-----------|--------------|-------------|---------------------|
|1411482360 | 001143792042 | 08444599175 | 2014-07-31 13:55:03 |
|1476992122 | 001143792042 | 08441713191 | 2014-07-31 14:05:10 |

The customer and company fields represents their telephone numbers.

  • The requirement is to compute the total 'gain' and total 'lost' values based on the following logic:

EDIT:

-Customer A calls Company A.
-If customer A calls Company B then Company B will have +1 gain and Company A will have +1 lost.
-If customer A calls Company C then Company C will have +1 gain and Company B will have +1 lost.
-If customer A calls Company C again then the spill/gain will not be affected.
-The gain/lost only comes into play once a 2nd call has been made by customer A.

- If a customer calls companies in this order: A, B, B, C, A, A, C, B, D the process should be like this:

A ->  
B ->  B +1 gain,  A +1 lost
B ->  
C ->  C +1 gain,  B +1 lost
A ->  A +1 gain,  C +1 lost
A ->  
C ->  C +1 gain,  A +1 lost
B ->  B +1 gain,  C +1 lost
D ->  D +1 gain,  B +1 lost

After above process we should have the total values as:

Company    Total gain    Total lost
  A            1             2            
  B            2             2       
  C            2             2         
  D            1             0     

I started working on this but it's wrong, it's just an ideea, it doesn't give me separate incremented gain and lost values based on the above conditions:

DROP TABLE IF EXISTS GetTotalGainAndLost;

CREATE TEMPORARY TABLE IF NOT EXISTS GetTotalGainAndLost
    AS 
        (
        SELECT SUM(count) as 'TotalGainAndLost', `date`, DAY(`date`) as 'DAY' 
        FROM (SELECT count(*) as 'count', customer, `date` 
            FROM (SELECT customer, company, count(*) AS 'count', DATE_FORMAT(`call_end`,'%Y-%m-%d') as 'date' 
                FROM calls 
                WHERE `call_end` LIKE CONCAT(2014, '-', RIGHT(CAST(concat('0', 01) AS CHAR),2),'-%')
                GROUP BY customer, company, DAY(`call_end`) ORDER BY `call_end` ASC)
            as tbl1 group by customer, `date` having count(*) > 1) 
        as tbl2 GROUP by `date`
        );

Select * from GetTotalGainAndLost;

DROP TABLE GetTotalGainAndLost;

This query doesn't show any results.

  • The desired output would be something like below:

Should be one row per company and date (total gain and lost calls by day in e.g. january)

|  company    |  totalGain |  totalLost  |     date     |  DAY  | 
|-------------|------------|-------------|--------------|-------|
| 08444599175 |     17     |       6     | 2014-07-01   |  1    |
| 08444599175 |     12     |      10     | 2014-07-02   |  2    |
| 08444599175 |      3     |       6     | 2014-07-02   |  3    |
| 08444599175 |   ....     |      ...    |     ...      | ...   |
| 08444599175 |      7     |       6     | 2014-07-31   | 31    |
7
  • Please edit your question and include sample output. Also, what happens if someone calls the same company multiple times? Interleaved? Your rules don't seem comprehensive. Jan 20, 2015 at 13:19
  • What should be the output using your example with companies A, B and C? Put the expected result in the question.
    – axiac
    Jan 20, 2015 at 13:45
  • ok, will put the desired output....
    – alex
    Jan 20, 2015 at 13:47
  • 1
    Anyway, SQL is not quite the appropriate tool to implement such rules. It's easier to select the data you need, apply the rules and do the calculations in the client code then store the produced stats into the database. This kind of rules sometimes change. Soon you will start adding exceptions (use a different way of counting for some companies, f.e.) and cramming these in SQL leads to unmanageable code easily. More, whatever language you use for the application, it provides you simpler ways to manipulate the strings than CONCAT(2014, '-', RIGHT(CAST(concat('0', 01) AS CHAR),2),'-%')
    – axiac
    Jan 20, 2015 at 13:55
  • And, by the way, the type of column call_start seems to be VARCHAR. Change it to DATETIME before anything else.
    – axiac
    Jan 20, 2015 at 13:56

4 Answers 4

5
+50

Simplification

Let denote N as the number times company has appeared. Lets try to simplify the formula in three simple rules.

  1. The first company that appear will has N - 1 gains, N loss.
  2. The mid company will has N gains, N loss.
  3. The last company will has N gains, N - 1 loss

Testing

In your example:

  • Starting with company A, and it appears 3 times.
  • Company B appears 3 times
  • Company C appears 2 times
  • End with company D that appears 1 times.

Result

Company      Gain           Lost  
  A            2             3            
  B            3             3       
  C            2             2         
  D            1             0    

Translate to SQL

First we start by counting the number appearance of each company.

SELECT
    company, COUNT(*) AS gain, COUNT(*) AS lost, DATE(call_start) AS date
FROM calls 
GROUP BY DATE(call_start), company

Then, we start select the number that each company appear the first time for each customer.

SELECT company, -COUNT(*) AS gain, 0 AS lost, DATE(call_start) AS `date`
FROM calls INNER JOIN (
    SELECT MIN(call_id) AS call_id FROM calls GROUP BY DATE(call_start), customer
) AS t ON (calls.call_id = t.call_id)
GROUP BY DATE(call_start), calls.company

The number of company that appear last.

SELECT company, 0 AS gain, -COUNT(*) AS lost, DATE(call_start) AS `date`
FROM calls INNER JOIN (
    SELECT MAX (call_id) AS call_id FROM calls GROUP BY DATE(call_start), customer
) AS t ON (calls.call_id = t.call_id)
GROUP BY DATE(call_start), calls.company

Combine SQL

Finally, we can combine the whole SQL together using UNION ALL and then do another group by.

SELECT company, SUM(gain) AS gain, SUM(lost) AS lost, `date` FROM (
    (
        SELECT
            company, COUNT(*) AS gain, COUNT(*) AS lost, DATE(call_start) AS `date`
        FROM calls 
        GROUP BY DATE(call_start), company
    ) UNION ALL (
        SELECT company, -COUNT(*) AS gain, 0 AS lost, DATE(call_start) AS `date`
        FROM calls INNER JOIN (
            SELECT MIN(call_id) AS call_id FROM calls GROUP BY DATE(call_start), customer
        ) AS t ON (calls.call_id = t.call_id)
        GROUP BY DATE(call_start), calls.company
    ) UNION ALL (
        SELECT company, 0 AS gain, -COUNT(*) AS lost, DATE(call_start) AS `date`
        FROM calls INNER JOIN (
            SELECT MAX(call_id) AS call_id FROM calls GROUP BY DATE(call_start), customer
        ) AS t ON (calls.call_id = t.call_id)
        GROUP BY DATE(call_start), calls.company
    )
) AS t
GROUP BY `date`, company

Clarification

The above query make assumption that each new day is independence. For example,

  • Customer A call Company A (Day 1)
  • Customer A call Company B (Day 1) B gains 1, A lost 1
  • Customer A call Company C (Day 1) C gains 1, B lost 1
  • Customer A call Company D (Day 2)
  • Customer A call Company E (Day 2) E gains 1, D lost 1

The result would be

COM   G     L   DAY
 ----------------
A     0     1    1
B     1     1    1
C     1     0    1
D     0     1    2
E     1     0    2
2
  • will try this and get back
    – alex
    Jan 22, 2015 at 15:06
  • @alex, I also make another assumption that the call_id is auto-increasement which mean that greater call_id means more latest call.
    – invisal
    Jan 22, 2015 at 15:10
3

I think the easiest way to do this is with two queries. First we can get total gains counting every call made to a different company by each customer:

select g.company company, count(g.call_id) gain
from calls c
join calls g on c.customer = g.customer and c.company <> g.company and c.call_start < g.call_start
left join calls m on g.customer = m.customer and g.company <> m.company and g.call_start > m.call_start and m.call_start > c.call_start
where m.call_id is null
group by g.company;

Left join is needed to don't count extra gains if customer makes various calls to various companies (i. e. if customer calls in order to company a, b and c company c only has one gain, not two).

Total lost with the same approach:

select l.company company, count(l.call_id) lost
from calls c
join calls l on c.customer = l.customer and c.company <> l.company and c.call_start > l.call_start
left join calls m on l.customer = m.customer and l.company <> m.company and c.call_start > m.call_start and l.call_start < m.call_start
where m.call_id is null
group by l.company;

Here's a little fiddle demoing the solution: http://sqlfiddle.com/#!2/3236ab/7

3

This should work -

CTEGains finds out how many times the company appears per customer per date.

CTEFirst finds out if the company was first contact for the customer on that day.

CTELast finds out if the company was the last contact for the customer on that day.

The code should then follow the logic that you pointed out.

CREATE TEMPORARY TABLE CTEGains (RNo int, customer varchar(14), company varchar(16), startdate date, gains int)
CREATE TEMPORARY TABLE CTEFirst (customer varchar(14), call_start date, company varchar(16))
CREATE TEMPORARY TABLE CTELast (customer varchar(14), call_start date, company varchar(16))
Insert into CTEGains
Select ROW_NUMBER() over (partition by customer order by Customer) Rno, customer, company, Convert(date,call_start) startdate, count(company) gains 
from calls
group by customer, company, Convert(date,call_start), call_start

Insert into CTEFirst
Select customer, min(Convert(date,call_start)) call_start, min(company) company
from calls
group by customer, Convert(date,call_start)

Insert into CTELast
Select customer, max(Convert(date,call_start)) call_start, max(company) company
from #calls
group by customer, Convert(date,call_start)

Select c1.company, 
SUM(gains) - case when exists (Select * from CTEGains c2 where c2.customer = max(c1.customer) and max(c1.Rno) = c2.Rno - 1 and c1.company = c2.company and c1.startdate = c2.startdate) then 1 else 0 end --Didn't gain as same company called
           - case when exists (select * from CTEFirst c2 where c2.company = c1.company and c2.call_start = c1.startdate) then 1 else 0 end TotalGain -- Didn't gain as first company
, SUM(gains) - case when exists (Select * from CTEGains c2 where c2.customer = max(c1.customer) and max(c1.Rno) = c2.Rno - 1 and c1.company = c2.company and c1.startdate = c2.startdate) then 1 else 0 end --Didn't lose as same company as last called
             - case when exists (select * from CTELast c2 where c2.company = c1.company and c2.call_start = c1.startdate) then 1 else 0 end TotalLost -- didn't lose as last company
, startdate [date], DatePart(DAY, startdate) [Day]
from CTEGains c1
group by c1.company, c1.startdate

Drop Table CTEFirst
Drop Table CTEGains
Drop Table CTELast
2
  • MySQL does not support CTEs
    – user330315
    Jan 29, 2015 at 11:56
  • Thanks for the heads up @a_horse_with_no_name I didn't realise MySQL didn't support CTEs. Jan 29, 2015 at 12:08
2

Let's first make some definitions:

  • Non-first call : any call which is not the first call of the customer that made it.
  • Non-last call : any call which is not the last call of the customer that made it.

We have introduced the concepts of first and last, so that means that we'll need to define a total order on our set of calls. We can follow any rule we want, but for the purposes of this explanation I've assumed that the calls are ordered by start time and, on equal start times, by id. In other words:

  • If callA.sartTime < callB.startTime, then callA < callB
  • If callA.startTime = callB.startTime and callA.id = callB.id, then callA < callB

Notice how we could obtain all the non-first calls of our set with the following query:

SELECT *
FROM calls AS non_first_calls
    RIGHT JOIN calls
    ON non_first_calls.customer = calls.customer
    AND non_first_calls.call_start >= calls.call_start
    AND non_first_calls.call_id > calls.call_id
WHERE non_first_calls.call_id IS NOT NULL

(the query output has duplicates, that is, calls can appear more than once)

Similarly, we can obtain all the non-last calls as follows:

SELECT *
FROM calls AS non_last_calls
    RIGHT JOIN calls
    ON non_last_calls.customer = calls.customer
    AND non_last_calls.call_start <= calls.call_start
    AND non_last_calls.call_id < calls.call_id
WHERE non_last_calls.call_id IS NOT NULL

Business logic

A company gains +1 every time a customer calls the company after having made any other call. That means that, for any given company, its gains are equal to the number of non-first-calls it has received. In the same way, a company's losses equal the amount of non-last-calls it has received.

The mighty query

So we only need to count, for every company, how many non-first calls and non-last calls it has received.

The for every company part means that we need to obtain a complete listing of companies. We can do that with this query:

SELECT DISTINCT company FROM calls

Putting it all together:

SELECT

    -- The company
    companies.company

    -- How many non-first calls (gains) it has received
    ,(SELECT COUNT(DISTINCT non_first_calls.call_id) gains
        FROM calls AS non_first_calls
        RIGHT JOIN calls
            ON non_first_calls.customer = calls.customer
            AND non_first_calls.call_start >= calls.call_start
            AND non_first_calls.call_id > calls.call_id
        WHERE non_first_calls.company = companies.company
    ) gains

    -- How many non-last calls (losses) it has received    
    ,(SELECT COUNT(DISTINCT non_last_calls.call_id) gains
        FROM calls AS non_last_calls
        RIGHT JOIN calls
            ON non_last_calls.customer = calls.customer
            AND non_last_calls.call_start <= calls.call_start
            AND non_last_calls.call_id < calls.call_id
    WHERE non_last_calls.company = companies.company
    ) losses

-- From the set of all companies
FROM (SELECT DISTINCT company FROM calls) companies

On performance

I'm not really sure that the efficiency of this query will be acceptable when working with a large volume of data.

At the very least you would need a combined index on (customer, call_start) (in this order) and another index on (company). This is the output I obtained after running EXPLAIN on this query with he mentioned indexes and the sample data you provided.

Output of EXPLAIN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.