I have a table that has a column called id. The table name is called names.
I need to show all the id’s that have one or more records on the table, and the corresponding fields on the table.
The search criteria is WHERE org = ‘A’. If I search just for org = ‘A’ then I will show only those records. I need to be able to also show the other records with the same id.
I tried
SELECT id, name, state, org
FROM names
WHERE
HAVING count(org) > 2
GROUP BY id, name, state, org
names table
id | name | state | org |
---|---|---|---|
111 | John | GA | A |
111 | April | FL | B |
112 | Max | GA | A |
113 | Alex | NC | C |
114 | Steve | SC | A |
114 | Rachel | AL | B |
114 | Brad | TN | D |
Desired output
id | name | state | org |
---|---|---|---|
111 | John | GA | A |
111 | April | FL | B |
114 | Steve | SC | A |
114 | Rachel | AL | B |
114 | Brad | TN | D |
Thanks
4
Answers
Your query could be:
Details:
tmp
CTE query helps calculate the number of rows with the sameid
,with the help of
count()
window function;'A'
org
-filter and thesame_id_count > 1
filter.DB fiddle
Extract the ids with more than one record and then use them to query
You need to check the existence of org = A records and then fetch the matching id records. Then filter the records having more than 1 count –
Demo.
To be able to select 2 or more records with the same id given a column value we can use the following query
The following query will first select all the id’s that have one or more records on the table, and the corresponding fields on the table. Then, it will use the IN operator to filter the results to only include rows with those id’s.
This will give the same output as the desired output displayed in your question.