0

I have a log table look like this

rpt_id | shipping_id | shop_id | status | create_time
-------------------------------------------------------------
1      | 1           | 600     | 1      | 2013-12-01 01:06:50
2      | 1           | 600     | 0      | 2013-12-01 01:06:55
3      | 1           | 600     | 1      | 2013-12-02 10:00:30
4      | 2           | 600     | 1      | 2013-12-02 10:00:30
5      | 1           | 601     | 1      | 2013-12-02 11:20:10
6      | 2           | 601     | 1      | 2013-12-02 11:20:10
7      | 1           | 601     | 0      | 2013-12-03 09:10:10
8      | 3           | 602     | 1      | 2013-12-03 13:15:58

And I want to use single query to make it look like this

shipping_id | total_activate | total_deactivate
-----------------------------------------------
1           | 2              | 2
2           | 2              | 0
3           | 1              | 0

How should I query this?

Note:

  • Status = 1 = Activate
  • Status = 0 = Deactivate
  • Count total activate / deactivate rule: look at log table above. rpt_id 1 & 3, it has same shop_id, shipping_id and status. It should only count as one. See the result table. Shipping id 1 is only activated by 2 shops, they are shop_id 600 and 601.

Can you guys advice me how to make the query? thanks for the help:D

1
  • 2
    No time to answer right now, but search for "crosstab" Commented Dec 12, 2013 at 3:24

2 Answers 2

1

Try this:

select shipping_id,
       sum(case when status=1 then 1 else 0 end) as total_activate,
       sum(case when status=0 then 1 else 0 end) as total_deactivate
from (select distinct shipping_id, 
                      shop_id, 
                      status
        from test) a
group by shipping_id
order by shipping_id

See it here at fiddle: http://sqlfiddle.com/#!15/f15fd/4

I did not put the date on the query as it is not important for the result.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes thanks... I also figured it out already, you can do it this way too.... thx

SELECT 
    shipping_id, 
    COUNT(DISTINCT CASE WHEN status = 1 THEN shop_id END) AS total_activate, 
    COUNT(DISTINCT CASE WHEN status = 0 THEN shop_id END) AS total_deactivate 
FROM 
    test

GROUP BY 
    shipping_id 
ORDER BY 
    shipping_id

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.