mysql - SQL Query to find rows that didn't occur this month -


i trying find number of sellers made sale last month didn't make sale month.

i have query works don't think efficient , haven't figured out how months.

select count(distinct user_id) users transactions month(date) = 12 , year(date) = 2015 , transactions.status = 'completed' , transactions.amount > 0 , transactions.user_id not in  (     select distinct user_id     transactions     month(date) = 1     , year(date) = 2016     , transactions.status = 'completed'     , transactions.amount > 0 ) 

the structure of table is:

+---------+------------+-------------+--------+ | user_id |    date    |   status    | amount | +---------+------------+-------------+--------+ |       1 | 2016-01-01 | 'completed' | 1.00   | |       2 | 2015-12-01 | 'completed' | 1.00   | |       3 | 2015-12-01 | 'completed' | 2.00   | |       1 | 2015-12-01 | 'completed' | 3.00   | +---------+------------+-------------+--------+ 

so in case, users id 2 , 3, didn't make sale month.

use conditional aggregation:

select count(*) users  (     select user_id     transactions                        -- 1st of previous month     date between subdate(subdate(current_date, dayofmonth(current_date)-1), interval 1 month)                         -- end of current month                    , last_day(current_date)     , transactions.status = 'completed'     , transactions.amount > 0     group user_id            -- row previous month     having max(case when date < subdate(current_date, dayofmonth(current_date)-1)                     date                 end) not null            -- no row in current month        , max(case when date >= subdate(current_date, dayofmonth(current_date)-1)                     date                 end) null             ) dt 

subdate(current_date, dayofmonth(current_date)-1) = first day of current month

subdate(first day of current month, interval 1 month) = first day of previous month

last_day(current_date) = end of current month


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -