Home Forums SQL Server 2008 T-SQL (SS2K8) Find Min of the Two columns when multiplied and Grouped RE: Find Min of the Two columns when multiplied and Grouped

  • There are many different ways to write a query to do this, here's a popular one:

    DECLARE @SampleData

    TABLE (

    id INTEGER NOT NULL,

    first INTEGER NOT NULL,

    sec INTEGER NOT NULL,

    group_id INTEGER NOT NULL,

    vid INTEGER NOT NULL,

    PRIMARY KEY CLUSTERED (id)

    );

    INSERT @SampleData

    VALUES (1, 1, 2, 16, 122),

    (3, 2, 1, 16, 122),

    (2, 3, 1, 08, 033),

    (4, 1, 5, 16, 012),

    (5, 1, 6, 16, 001);

    SELECT *

    FROM (

    SELECT *,

    row_num =

    ROW_NUMBER() OVER (

    PARTITION BY S.group_id

    ORDER BY S.first * S.sec ASC)

    FROM @SampleData S

    ) S

    WHERE S.row_num = 1;