Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to GROUP and choose lowest value in SQL

I have table consisting of these fields:

 id  |   date_from  | date_to      |   price
 --------------------------------------------
 CK1     22-12-2012   29-12-2012       800
 CK1     22-12-2012   29-12-2012       1200
 CK2     22-12-2012   29-12-2012       1400
 CK2     22-12-2012   29-12-2012       1800
 CK2     22-12-2012   29-12-2012       2200

How do I create SQL select that groups results by ID, DATE_FROM, DATE_TO and picks lowest value from price.

So result would be

 CK1     22-12-2012   29-12-2012       800
 CK2     22-12-2012   29-12-2012       1400
like image 612
feronovak Avatar asked Mar 27 '12 08:03

feronovak


People also ask

How do you select the lowest value in SQL?

Use the MIN function to select the record with the smallest value of the Price column.

How do I select a row with minimum value in SQL?

To select data where a field has min value, you can use aggregate function min(). The syntax is as follows. SELECT *FROM yourTableName WHERE yourColumnName=(SELECT MIN(yourColumnName) FROM yourTableName);

Can we use MIN function in WHERE clause?

The SQL MIN() function with WHERE clauseThe aggregate functions can be used in conjunction with the WHERE clause to gain further insights from our data. One of these is the MIN() function. In SQL, the MIN() function is used to compute the smallest or minimum value of numeric values in a column.

How do you select the bottom 3 rows in SQL?

SELECT * FROM (select * from suppliers ORDER BY supplier_name DESC) suppliers2 WHERE rownum <= 3 ORDER BY rownum DESC; Notice that although you want the last 3 records sorted by supplier_name in ascending order, you actually sort the supplier_name in descending order in this solution.


2 Answers

select id, date_from, date_to, min(price)
from table
group by id, date_from, date_to
like image 116
Phil Avatar answered Nov 08 '22 19:11

Phil


If your dbms support cte then you can do like this;

Test data

DECLARE @tbl TABLE
(
    id VARCHAR(100),
    date_from VARCHAR(100),
    date_to VARCHAR(100),
    price INT
)

INSERT INTO @tbl
VALUES
    ('CK1','22-12-2012','29-12-2012',800),
    ('CK1','22-12-2012','29-12-2012',1200),
    ('CK2','22-12-2012','29-12-2012',1400),
    ('CK2','22-12-2012','29-12-2012',1800),
    ('CK2','22-12-2012','29-12-2012',2200)

Query

;WITH CTE
AS
(   
    SELECT
        RANK() OVER(PARTITION BY id ORDER BY price ASC) AS RowNbr,
        tbl.*
    FROM
        @tbl AS tbl
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.RowNbr=1
like image 20
Arion Avatar answered Nov 08 '22 21:11

Arion