In Postgres I have a properties
table with following columns: item, user, property
. Each item is unique and belongs to a unique user. Each user can have multiple items. But properties are not uniques, ie, the same property can be the same for many items. eg,
item, user, property
--------------------
item1 user1 property1
item1 user1 property2
item2 user1 property1
item2 user1 property3
item2 user1 property4
item3 user2 property2
item3 user2 property4
Now I want to calculate how many unique users have the given property in their items, ie, in this case I need to get:
property1 1
property2 2
property3 1
property4 2
I can think of an SQL query for that like this:
SELECT COUNT(*), x.property
FROM (SELECT user, property
FROM properties
GROUP BY user, property) x
GROUP BY x.property;
Is there a better way to do this? Thanks!
select count(distinct user), property
from properties
group by property
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.