Compare one field between two rows in the same table - sql

I have a small table which contains group memberships to which I am struggling to find a query.
uid groupid userid
1 2 5
2 2 6
3 1 2
4 3 8
5 4 7
I was wondering if it is possible to return TRUE if two given user IDs where in the same group?

The following gets all groups that have two given members:
select groupid
from table t
where userid in ($userid1, $userid2)
group by groupid
having count(distinct userid) = 2;
You can turn this into a boolean if you like:
select (case when count(*) > 0 then true else false end)
from (select groupid
from table t
where userid in ($userid1, $userid2)
group by groupid
having count(distinct userid) = 2
) g;

SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN "TRUE" ELSE "FALSE" END
FROM my_table
WHERE userid IN ('x', 'y')
GROUP BY groupid
Note the x and y should be replaced with the given userids
TRUE:
SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN 'TRUE' ELSE 'FALSE' END
FROM my_table
WHERE userid IN (5,6)
GROUP BY groupid
FALSE:
SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN 'TRUE' ELSE 'FALSE' END
FROM my_table
WHERE userid IN (5,2)
GROUP BY groupid
http://sqlfiddle.com/#!15/3f156/1

UNIQUE userid
Each user can only have at most one entry (like the question seems to ask).
SELECT (SELECT groupid FROM tbl WHERE userid = 5)
= (SELECT groupid FROM tbl WHERE userid = 6);
Assuming useridis UNIQUE.
Returns TRUE or FALSE exactly like requested.
- or NULL if a userid is not found or groupid is NULL.
UNIQUE (userid, groupid)
Each user can only have multiple entries (as clarified in the comment):
Share all groups?
SELECT EXISTS (
SELECT 1
FROM (SELECT groupid FROM tbl2 WHERE userid = 5) a
FULL JOIN (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid)
WHERE a.groupid IS NULL OR
b.groupid IS NULL
) AS share_all;
Share at least one group?
SELECT EXISTS (
SELECT groupid FROM tbl2 WHERE userid = 8
INTERSECT
SELECT groupid FROM tbl2 WHERE userid = 9
) AS share_min_one;
Or
SELECT EXISTS (
SELECT 1
FROM (SELECT groupid FROM tbl2 WHERE userid = 5) a
JOIN (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid)
) AS share_min_one;
Share exactly one group?
SELECT count(*) = 1 AS share_exactly_one
FROM (SELECT groupid FROM tbl2 WHERE userid = 5) a
JOIN (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid);
SQL Fiddle with better test data.
All of these queries are fast with an index on userid. Faster with a multicolumn index on (userid, groupid) in Postgres 9.2+.
Ultimately this is a case of relational-division. Here's an arsenal of query techniques:
How to filter SQL results in a has-many-through relation

Related

Postgresql combine IN with NOT IN

I have a table of entities where each can have different statuses. For the sake of keeping history, each status change is reflected by a new row.
Example:
Entity Id Status
123456 1
123456 2
789000 1
Assuming i want to find all rows that have only status 1 (so if they have other statuses they should not be returned), How do I do that?
This query:
select entityid
from tablename
group by entityid
having min(status) = 1 and max(status) = 1
returns all the entityids that you want, so you can use it with the operator IN:
select * from tablename
where entityid in (
select entityid
from tablename
group by entityid
having min(status) = 1 and max(status) = 1
)
Just use not exists:
select t.*
from t
where not exists (select 1
from t t2
where t2.entity_id = t.entity_id and t2.status <> 1
);

How to select value that matches all values in a list?

I am trying to get two separate row values, for 2 conditions on the same column.
for example with this data:
id status
----------------
1 0
1 2
1 3
2 2
2 0
I want to select all the rows where the status = 0, and status = 2.
So for example the output should be:
id status
----------------
1 0
1 2
2 0
2 2
Thank you!
One method is:
where status in (0, 2)
But I suspect you want both values for the id. In that case, one method uses exists:
select t.*
from t
where status in (0, 2) and
exists (select 1
from t t2
where t2.id = t.id and
t2.status in (0, 2) and
t2.status <> t.status
);
If you just want the ids, then aggregation is easy:
select id
from t
where status in (0, 2)
group by id
having count(*) = 2;
This can be incorporated in a query to get the original rows using in, exists, or join. Or window functions:
select t.*
from (select t.*,
count(*) filter (where status in (0, 2)) over (partition by id) as cnt
from t
) t
where cnt = 2;
Using HAVING COUNT(DISTINCT status) = 2, you can filter and get the id, and based on the ids using sub query with WHERE clause you can achieve the expected output:
SELECT *
FROM TableName
WHERE ID IN (
SELECT id
FROM TableName
WHERE status IN (0, 2)
GROUP BY id
HAVING COUNT(DISTINCT status) = 2
) AND status IN (0, 2)
Working demo on db<>fiddle
To get the ids that you want you need to group by id and count the distinct values of status:
select * from tablename
where
status in (0, 2)
and
id in (
select id from tablename
where status in (0, 2)
group by id
having count(distinct status) = 2
)

SQL query to return rows where only one record is present in a given status

I have a table with data similar to below. I am trying to get a list of results that will display all rows where only one unique SourceID exists in status 10. If I were querying this table, I would expect ID's 3 and 4 to be returned.
Table Example
Select *
From table
Where Status = 10 and Source ID in
(
Select SourceID
From Table
Group by SourceID
Having Count(*) = 1
)
You can use NOT EXISTS :
SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.SourceID = t.SourceID AND t1.Status <> t.Status);
Maybe that would work?
SELECT ID FROM Mytable
WHERE [Status] = 10
GROUP BY ID
HAVING COUNT(SourceID) = 1
First, find out all the unique SourceIDs
SELECT
SourceID
FROM
Data
GROUP BY
SourceID
HAVING
COUNT(SourceID) = 1
And then use this query as a sub query to get all the rows that has unique SourceID;
SELECT
*
FROM
Data
WHERE
SourceID IN (
SELECT
SourceID
FROM
Data
GROUP BY
SourceID
HAVING
COUNT(SourceID) = 1
)
Use a sub-query to check if t there is an exact count of 1 of those source id's
SELECT t.* FROM YourTable t WHERE t.status = 10
AND
(SELECT COUNT(0) x From YourTable t2
where t2.sourceid = t.sourceid) = 1

Find out particular id

I have a table in sql like this:
id billpay
-------------------------
1024 0
1024 0
1024 1
1025 1
1025 1
I want to retrieve only those id having billpay 1
Please help me with this
Try this:
select distinct id from yourtable where billpay = 1
It should be like this:
SELECT id FROM tabel WHERE billpay = 1;
This will retrieve those ids in ascending order which have at least one record in the table with billpay = 1.
The DISTINCT keyword will ensure you don't receive back multiple records with the same id.
SELECT DISTINCT id
FROM [TableName]
WHERE billpay = 1
ORDER BY id ASC
If you want to exclude those ids which also have records with billpay = 0, then use this:
SELECT DISTINCT id
FROM [TableName]
WHERE billpay = 1
AND id NOT IN (SELECT id FROM [TableName] WHERE billpay = 0)
ORDER BY id ASC
Regards,
select ID
from MyData
Where billpay = 1
Group By ID
The group by will list unique IDs
select ID
from MyData A
Where not exists (select 'X' from MyData B where B.billpay <> 1 and B.ID = A.ID)
Group By ID
This will only list IDs where billpay is only 1
Try this:
SELECT id
FROM mytable
GROUP BY id
HAVING COUNT(CASE WHEN COALESCE(billpay, 0) <> 1 THEN 1 END) = 0
The above will select only those ids associated to billpay=1 and nothing but billpay=1.
SQL Fiddle Demo
The following query selects the ids from group of ids where the number of records with billpay = 1 is the same as the number of records in the group
select id
from bills
group by id
having sum(billpay) = count(id)
Use NOT EXISTS to find rows with no other than billplay 1, use DISTINCT to return only one of each id found.
select distinct id
from tablename t1
where not exists (select 1 from tablename t2
where t1.id = t2.id
and t2.billpay <> 1)
Try to use GROUP BY +MIN statement to exclude Id's with existing billpay=0
SELECT id
FROM yourtable
GROUP BY id
HAVING MIN(billpay)=1

how to get duplicates when I group rows?

I have this table:
MyTable(ID, FK, ...)
I am using this query:
select ID fromMytable were FK <> 1
group by ID, FK
order by ID
This gives me the result that I want:
255
255
267
268
790
...
The 255 is duplicate because has two differnt KFs. The rest of the IDs has the same FK. I would like to get the IDs which has more than one FK and has differents values.
If an ID has two rows with FK = 2 and FK = 3 then get this ID, but if the ID has FK = 2, FK = 2, FK = 2 I don't want this ID because it has the same FK.
How could I get this IDs?
Thank you so much.
You should count distinct FKs
select ID from Mytable where FK <> 1
group by ID
having count(distinct FK) > 1
order by ID
Try this:
SELECT
ID, COUNT(*)
FROM
fromMytable
WHERE
FK <> 1
GROUP BY
ID
HAVING
COUNT(*) > 1
ORDER BY ID
Use HAVING to find only ID that exists more one once:
select DISTINCT ID
from Mytable
where FK <> 1
group by ID, FK
having count(*) >= 2
order by ID
You can use ROW_NUMBER window function.
SELECT ID FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) RN, ID
from Mytable WHERE FK <> 1
) TMP
WHERE RN = 1