mysql 两个select结果_在MySQL中减去两个Select查询的结果

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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 ;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值