Postgresql – How to get the minimum sum value of fields without repeating where clause

postgresql

How can I get the minimum value after adding value of 2 fields without repeating the where clause?

Example: Get records with minimum value of num1 + num2 and deleted_at is null

id          num1        num2       deleted_at
----------  ---------   ---------  ---------  
1           1           1          2015-01-01
2           2           2          null
3           2           2          null         
4           4           4          null 

Expected result is

id          num1        num2       deleted_at
----------  ---------   ---------  ---------
2           2           2          null   
3           2           2          null

I tried subquery, but I have to repeat the where clause

SELECT * 
FROM   foos t1 
WHERE  t1.num1 + t1.num2 = (SELECT Min(t2.num1 + t2.num2) 
                            FROM   foos t2 
                            WHERE  t2.deleted_at IS NULL) //repeat
       AND t1.deleted_at IS NULL //repeat

Best Answer

In Sql Server , you can do it with RANK

CREATE TABLE foos
    ([id] int, [num1] int, [num2] int, [deleted_at] datetime)
;

INSERT INTO foos
    ([id], [num1], [num2], [deleted_at])
VALUES
    (1, 1, 1, '2015-01-01'),
    (2, 2, 2, NULL),
    (3, 2, 2, NULL),
    (4, 4, 4, NULL)
;

--the select

SELECT [id], [num1], [num2]
FROM 
(
 SELECT [id], [num1], [num2]
  , RANK() OVER(ORDER BY [num1]+ [num2] ASC) as rk
 FROM foos
 WHERE [deleted_at] IS NULL
)as r
WHERE r.rk = 1 

output:

id  num1    num2
2      2    2
3      2    2

dbfiddle here