如何在MySQL中使用额外的where子句选择count(distinct)?

时间:2014-12-08 18:45:01

标签: mysql sql select

我有一个如下所示的查询:

SELECT clicks.offer_id, count(distinct clicks.transaction_id) as unique_clicks
FROM clicks
WHERE date > '2014-12-01 17:43:30' and offer_id = 1;

此查询按商品的交易ID计算唯一点击次数。

现在,我想为移动和桌面用户添加唯一的点击次数。沿着:

SELECT clicks.offer_id, count(distinct clicks.transaction) as unique_clicks, 
     sum(case when clicks.mobile = 1 then 1 else 0 end) as mobile_unique_clicks, 
     sum(case when clicks.mobile = 0 then 1 else 0 end) as desktop_unique_clicks
FROM clicks
WHERE date > '2014-12-01 17:43:30' and offer_id = 1;

这样做的问题是它不会计算唯一的事务ID。有没有办法用一个查询来做到这一点?我需要什么样的覆盖指数才能保持这种效率?

3 个答案:

答案 0 :(得分:1)

SELECT clicks.offer_id, count(distinct clicks.transaction_id) as unique_clicks, 
     count(DISTINCT case when clicks.mobile = 1 then clicks.transaction_id else null end) as mobile_unique_clicks, 
     count(DISTINCT case when clicks.mobile = 0 then clicks.transaction_id else null end) as desktop_unique_clicks
FROM clicks
WHERE date > '2014-12-01 17:43:30' and offer_id = 1;

您可以使用COUNT(DISTINCT ...)

答案 1 :(得分:1)

这样的事情?

SELECT clicks.offer_id,
       count(distinct clicks.transaction_id) as unique_clicks,
       sub.mobile_unique_clicks, 
       count(distinct clicks.transaction_id) - sub.mobile_unique_clicks as desktop_unique_clicks
FROM clicks
JOIN 
(
   SELECT clicks.offer_id, count(distinct clicks.transaction_id) as mobile_unique_clicks,
   FROM clicks
   WHERE date > '2014-12-01 17:43:30' and offer_id = 1 AND  clicks.mobile = 1
) sub
WHERE date > '2014-12-01 17:43:30' and offer_id = 1;

答案 2 :(得分:0)

如果我正确理解您的问题,您可以将查询移至subquery并使用distinct

select offer_id, 
       count(transaction) unique_clicks,
       count(case when mobile = 1 then 1 end) mobile_unique_clicks,
       count(case when mobile = 0 then 1 end) desktop_unique_clicks
from (
       select distinct offer_id, transaction, mobile
       from clicks
       where date > '2014-12-01 17:43:30' and offer_id = 1
) t
group by offer_id