Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge these queries and create a single query

I have these three working queries:

SELECT a, time, b, c 
FROM table_first 
WHERE created_at >= timestamp '2022-02-13 00:00:00' 
  AND a = 'LK0601' 
ORDER BY time DESC
LIMIT 1;
SELECT a, time, b, c 
FROM table_first 
WHERE created_at >= timestamp '2022-02-13 00:00:00' 
  AND a = 'DT9834'
ORDER BY time DESC
LIMIT 1;
SELECT a, time, b, c 
FROM table_first 
WHERE created_at >= timestamp '2022-02-13 00:00:00' 
  AND a = 'LM3526' 
ORDER BY time DESC
LIMIT 1;

In these queries, I get the latest entry for the different values of a.

How can I merge them into one query?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So that it becomes something like the following:

SELECT a, time, b, c 
FROM table_first 
WHERE created_at >= timestamp '2022-02-13 00:00:00' 
  AND a IN ('LM3526','DT9834','LK0601') 
GROUP BY a 
ORDER BY time DESC
LIMIT 1;

From the above query, I want to get the latest rows for all the different values of a.

I am using the PostgreSQL database.

>Solution :

You may use DISTINCT ON here:

SELECT DISTINCT ON (a) a, time, b, c
FROM table_first
WHERE created_at >= timestamp '2022-02-13 00:00:00' AND
      a IN ('LK0601', 'DT9834', 'LM3526')
ORDER BY a, time DESC;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading