Skip to content

Instantly share code, notes, and snippets.

@terrafied
Created July 27, 2012 20:04
Show Gist options
  • Save terrafied/3190184 to your computer and use it in GitHub Desktop.
Save terrafied/3190184 to your computer and use it in GitHub Desktop.
SQL query
Tables:
-users
-timestamps
-enterprises
-enterprise_users
-user_id
-enterprise_id
Goal:
Trying to find a query for all users for a given enterprise, but only for users for ONLY that enterprise. In otherwords, if a user is part of more than one enterprise (can assume simply more than one enterprise_users record for that user_id), then I *don't* want that returned.
Query so far:
SELECT COUNT(*) AS count_all, enterprise_users.enterprise_id AS enterprise_users_enterprise_id FROM `users` INNER JOIN `enterprise_users` ON `enterprise_users`.`user_id` = `users`.`id` WHERE (users.created_at > date('2012-02-01') AND users.created_at < date('2012-03-01') AND enterprise_users.enterprise_id = 1) GROUP BY enterprise_users.enterprise_id HAVING count(enterprise_users.enterprise_id) < 2
But this returns zero results. I know the results for both "this enterprise" and "ONLY this enterprise"
@jmelesky
Copy link

with
alluserlist as (select user_id from enterprise_users where enterprise_id = 1),
onlyuserlist as (select user_id from alluserlist, enterprise_users
where alluserlist.user_id = enterprise_users.user_id
group by user_id having count() < 2)
select count(
)
from onlyuserlist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment