如何在SQL中选择GROUP并选择最低值

时间:2012-03-27 08:30:23

标签: sql tsql select group-by

我的表包含以下字段:

 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

如何创建SQL选择按ID,DATE_FROM,DATE_TO分组结果并从价格中选择最低值。

结果将是

 CK1     22-12-2012   29-12-2012       800
 CK2     22-12-2012   29-12-2012       1400

4 个答案:

答案 0 :(得分:22)

select id, date_from, date_to, min(price)
from table
group by id, date_from, date_to

答案 1 :(得分:4)

像这样:

SELECT id, date_from, date_to, MIN(price)
FROM TableName
GROUP BY id, date_from, date_to

答案 2 :(得分:4)

如果您的dbms支持cte,那么您可以这样做;

测试数据

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)

<强>查询

;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

答案 3 :(得分:0)

SELECT id, date_from, date_to, min(price)
FROM my_table
GROUP BY id, date_from, date_to