2

If I have a table like this:

id   name   value
1    abc      1
2    def      4
3    ghi      1
4    jkl      2

How can I select a new table that still has id, name, value but only the ones with a minimum value.

In this example I need this table back:

1  abc 1
3  ghi 1
3
  • 1
    What's your DBMS? If it supports ROW_NUMBER it's simple. Commented Nov 10, 2016 at 18:40
  • @dnoeth I'm using postgresql Commented Nov 10, 2016 at 18:41
  • Check @Lamak's answer, this is even simpler. Commented Nov 10, 2016 at 18:43

3 Answers 3

10

Finding those values is pretty straightforward:

SELECT *
FROM YourTable
WHERE value = (SELECT MIN(Value) FROM YourTable);

As for the right syntax for putting those rows in another table, that will depend on the database engine that you are using.

Sign up to request clarification or add additional context in comments.

Comments

2

An alternative to @Lamak's solution could be to use the rank window function. Depending on the exact scenario, it may perform quite better:

SELECT id, name, value
FROM   (SELECT id, name, value, RANK() OVER (ORDER BY value ASC) AS rk
        FROM   mytable) t
WHERE  rk = 1

2 Comments

I like this as well as you could specify a specific rank 2, 3, 4, etc to get a specific rank outside of min or max.
@xQbert It is more general solution but raises the scan and caching of the whole table.
1

not sure exactly if this is what you're trying to do, but I think this would work:

    --creating #temp1 to recreate your table/example
     CREATE TABLE #TEMP1
    (id      INT       NOT NULL PRIMARY KEY, 
     name    CHAR(3)   NOT NULL,
     value   INT       NOT NULL)


    INSERT INTO #TEMP1
    VALUES 
    (1,'abc',1), 
    (2,'def',4), 
    (3,'ghi',1), 
    (4,'jkl',2)

    -verify correct

    SELECT * FROM #temp1

    --populate new table with min value from table 1

    SELECT *
    INTO #TEMP2
    FROM #TEMP1
    WHERE value = (SELECT MIN(value) 
                   FROM #TEMP1)

    SELECT * FROM #TEMP2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.