Get the Jaws of Life
Get the Jaws of Life

Reputation: 435

MySQL SUM DISTINCT with Conditional

I need to gather sums using conditional statements as well as DISTINCT values with a multiple GROUP BY. The example below is a simplified version of a much much more complex query.

Because the real query is very large, I need to avoid having to drastically re-write the query.

DATA

Contracts
    id  advertiser_id   status
    1   1               1
    2   2               1
    3   3               2
    4   1               1

A Query that's close

SELECT
    COUNT( DISTINCT advertiser_id ) AS advertiser_qty,
    COUNT( DISTINCT id ) AS contract_qty,
    SUM( IF( status = 1, 1, 0 ) ) AS current_qty,
    SUM( IF( status = 2, 1, 0 ) ) AS expired_qty,
    SUM( IF( status = 3, 1, 0 ) ) AS other_qty
FROM (
        SELECT * FROM  `contracts`
        GROUP BY advertiser_id, id
) AS temp

Currently Returns

advertiser_qty  contract_qty    current_qty     expired_qty     other_qty   
3               4               3               1               0

Needs to Return

advertiser_qty  contract_qty    current_qty     expired_qty     other_qty   
3               4               2               1               0

Where current_qty is 2 which is the sum of records with status = 1 for only DISTINCT advertiser_ids and each sum function will need the same fix.

I hope someone has a simple solution that can plug into the SUM functions.

-Thanks!!

Upvotes: 4

Views: 16968

Answers (1)

echo_Me
echo_Me

Reputation: 37233

try this

    SELECT
    COUNT( DISTINCT advertiser_id ) AS advertiser_qty,
    COUNT( DISTINCT id ) AS contract_qty,
    (select count(distinct advertiser_id) from contracts where status =1 
    ) AS current_qty,

   SUM( IF( status = 2, 1, 0 ) ) AS expired_qty,
   SUM( IF( status = 3, 1, 0 ) ) AS other_qty
   FROM (
   SELECT * FROM  `contracts`
   GROUP BY advertiser_id, id
   ) AS temp

DEMO HERE

EDIT:

you may look for this without subselect.

 SELECT COUNT(DISTINCT advertiser_id) AS advertiser_qty,
        COUNT(DISTINCT id) AS contract_qty,
        COUNT(DISTINCT advertiser_id , status = 1) AS current_qty,
        SUM(IF(status = 2, 1, 0)) AS expired_qty,
        SUM(IF(status = 3, 1, 0)) AS other_qty
 FROM (SELECT *
       FROM   `contracts`
       GROUP BY advertiser_id, id) AS temp

DEMO HERE

Upvotes: 3

Related Questions