简体   繁体   中英

select resultset of counts by array param in postgres

I've been searching for this and it seems like it should be something simple, but apparently not so much. I want to return a resultSet within PostgreSQL 9.4.x using an array parameter so:

| id | count |
--------------
| 1  |   22  |
--------------
| 2  |   14  |
--------------
| 14 |   3   |

where I'm submitting a parameter of {'1','2','14'} .

Using something (clearly not) like:

SELECT id, count(a.*) 
FROM tablename a
WHERE a.id::int IN array('{1,2,14}'::int);

I want to test it first of course, and then write it as a storedProc (function) to make this simple.

Forget it, here is the answer:

SELECT a.id,
       COUNT(a.id)
FROM tableName a
WHERE a.id IN
    (SELECT b.id 
     FROM tableName b
     WHERE b.id = ANY('{1,2,14}'::int[])
    )
GROUP BY a.id;

You can simplify to:

SELECT id, count(*) AS ct
FROM   tbl
WHERE  id = ANY('{1,2,14}'::int[])
GROUP  BY 1;

More:

To include IDs from the input array that are not found I suggest unnest() followed by a LEFT JOIN :

SELECT id, count(t.id) AS ct
FROM   unnest('{1,2,14}'::int[]) id
LEFT   JOIN tbl t USING (id)
GROUP  BY 1;

Related:

If there can be NULL values in the array parameter as well as in the id column (which would be an odd design), you'd need (slower!) NULL-safe comparison:

SELECT id, count(t.id) AS ct
FROM   unnest('{1,2,14}'::int[]) id
LEFT   JOIN tbl t ON t.id IS NOT DISTINCT FROM id.id
GROUP  BY 1;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM