开发者

Combine these mySQL queries

I need to combine these queries, so i get back a list of months, with a new total, and returning total (to track new and returning users). I currently have these two queries below. The first counts devices w开发者_如何学运维hich are new (detection freq), the second counts as returning. I want to output the results so it's a table with rows for each month, then two columns with New, and Returning data.

SELECT COUNT( DISTINCT (mac) ) AS new,
EXTRACT( MONTH FROM date_time ) AS month
FROM detected_devices
WHERE client_id = 11
AND venue_id = 1
AND detection_frequency = 1
GROUP BY month

UNION ALL

SELECT COUNT( DISTINCT (mac) ) AS returning,
EXTRACT( MONTH FROM date_time ) AS month
FROM detected_devices
WHERE client_id = 11
AND venue_id = 1
AND detection_frequency > 1
GROUP BY month

I have had a look around but not found any information on how this can be done with aliases.


What about this ?

SELECT t1.month, t1.new, t2.returning FROM (query 1) as t1, (query 2) as t2 where t1.month = t2.month;

(or a join, depending on what you prefer).


This only gives you one row with two columns, but should give you an idea of how you can use aliases

SELECT
A.new,
B.returning
FROM
(SELECT COUNT( DISTINCT (mac) ) AS new,
EXTRACT( MONTH FROM date_time ) AS month
FROM detected_devices
WHERE client_id = 11
AND venue_id = 1
AND detection_frequency = 1
GROUP BY month) A,
(SELECT COUNT( DISTINCT (mac) ) AS returning,
EXTRACT( MONTH FROM date_time ) AS month
FROM detected_devices
WHERE client_id = 11
AND venue_id = 1
AND detection_frequency > 1
GROUP BY month) B
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜