Return one SQL row per product with price and latest date

前端 未结 6 1100
南旧
南旧 2021-01-24 03:35

I am not a SQL guy, I have used it in the past and rarely have an issue that cant be solved by google... however this time I need to ask the Community.

I have a database

6条回答
  •  执念已碎
    2021-01-24 04:21

    One method uses the ROW_NUMBER windowed function.

    My query uses a common table expression (CTE) to provide sample data. When using this technique you always need a CTE, or subquery. This is because values generated in the SELECT clause are not available to the WHERE clause. This is a consequence of something called the Logical Processing Order. In other words; SQL Server generates the row numbers after it has filtered the data. CTEs/Subqueries provide you with a second WHERE clause, that is actioned after the row numbers have been generated**.

    -- Returning the most recent record from a transaction table.
    WITH SampleDate AS
        (
            SELECT
                ROW_NUMBER() OVER (PARTITION BY ProdNo ORDER BY TransactionDate DESC) AS Rn,
                *
            FROM
                (
                    VALUES                      
                        ('3STRFLEX', 13.02, '20162911', 'AWC '),
                        ('3STRFLEX', 15.02, '20162011', 'DWC '),
                        ('3STRFLEX', 15.02, '20160101', 'AWC '),
                        ('AFTV2'   , 35.49, '20162708', 'AWC '),
                        ('AFTV2'   , 29.99, '20160106', 'DWC '),
                        ('AFTV2'   , 29.99, '20160205', 'AWC ')
                ) AS x(ProdNo, Price, TransactionDate, PurchasedBy)
        )
    SELECT
        *
    FROM
        SampleDate
    WHERE
        Rn = 1
    ;
    

    ** Actually this isn't entirely true. It is called the logical order for a reason. SQL Sever can/will exeucte your queries any way it sees fit. But however your query is physically executed it will respect the logical order.

提交回复
热议问题