Subtract results of two Select queries in Mysql

我只是一个虾纸丫 提交于 2019-12-24 07:52:17

问题


I have written two mysql queries, one fetches me the total users(registered) present in a particular month of the year and the other fetches the active users in that particular month of the year. I need to find the number of inactive users for that year. For this, I was thinking of subtracting the totalUsers and the activeUsers columns obtained through two separate queries. Below are the queries

1. Fetch Total Registered users

set @numberOfUsers := 0; 
SELECT T.createdMonth, T.monthlyusers, (@numberOfUsers := @numberOfUsers + T.monthlyusers) as totalUsers 
FROM 
(
SELECT month(from_unixtime(u.createdDate)) as createdMonth, count(u.id) as monthlyusers
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016'  
group by month(from_unixtime(u.createdDate))    
) T;

2. Fetch Active Users

select month(from_unixtime(lastActive)), (count(u.id))  as activeUsers from user u 
where year(from_unixtime(lastActive)) = '2016' 
group by month(from_unixtime(lastActive));

I need to subtract activeUsers from totalUsers. How do i achieve this?


回答1:


you can simply subtract two query or merge

select (select query) - (select query);

SET @numberOfUsers := 0; 

SELECT l.totalUsers-a.monthlyusers FROM (SELECT T.createdMonth, 
T.monthlyusers, (@numberOfUsers := @numberOfUsers + T.monthlyusers) AS totalUsers 
FROM 
(
SELECT MONTH(FROM_UNIXTIME(u.createdDate)) AS createdMonth, COUNT(u.id) AS monthlyusers
FROM USER u 
WHERE YEAR(FROM_UNIXTIME(u.createdDate)) = '2016'  
GROUP BY MONTH(FROM_UNIXTIME(u.createdDate))    
) T ) l,(SELECT MONTH(FROM_UNIXTIME(lastActive)), (COUNT(u.id))  AS  activeUsers FROM USER u 
WHERE YEAR(FROM_UNIXTIME(lastActive)) = '2016' 
GROUP BY MONTH(FROM_UNIXTIME(lastActive))) a ;


来源:https://stackoverflow.com/questions/40735190/subtract-results-of-two-select-queries-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!