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
Use the MIN function to select the record with the smallest value of the Price column.
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);
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.
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.
select id, date_from, date_to, min(price)
from table
group by id, date_from, date_to
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With