SQL - 删除重复项以显示最新的日期记录

时间:2012-12-12 15:54:07

标签: sql tsql sql-server-2008-r2

我有一个观点,最终我希望每个客户返回1行。

目前其选择如下;

SELECT 
    Customerid,
    MAX(purchasedate) AS purchasedate,
    paymenttype,
    delivery,
    amount,
    discountrate 
FROM    
    Customer 
GROUP BY
    Customerid,
    paymenttype,
    delivery,
    amount,
    discountrate

我希望MAX(购买者)能够正常工作,但是当我进行分组时,它会中断,因为有时可能会有折扣,有时它的NULL,支付类型也会因为每个客户而有所不同,无论如何只是为了显示上次购买顾客会做什么?

1 个答案:

答案 0 :(得分:8)

因为SQL Server 2008 r2支持windows函数,

SELECT  Customerid,
        purchasedate,
        paymenttype,
        delivery,
        amount,
        discountrate
FROM    
    (
        SELECT  Customerid,
                purchasedate,
                paymenttype,
                delivery,
                amount,
                discountrate,
                ROW_NUMBER() OVER (Partition By CustomerID
                                    ORDER BY purchasedate DESC) rn
        FROM    Customer
    ) derivedTable
WHERE   derivedTable.rn = 1

或使用Common Table Expression

WITH derivedTable
AS
(
    SELECT  Customerid,
            purchasedate,
            paymenttype,
            delivery,
            amount,
            discountrate,
            ROW_NUMBER() OVER (Partition By CustomerID
                                ORDER BY purchasedate DESC) rn
    FROM    Customer
)
SELECT  Customerid,
        purchasedate,
        paymenttype,
        delivery,
        amount,
        discountrate
FROM    derivedTable
WHERE   derivedTable.rn = 1

或使用与在其他DBMS中工作的子查询的连接

SELECT  a.*
FROM    Customer a
        INNER JOIN
        (
            SELECT  CustomerID, MAX(purchasedate) maxDate
            FROM    Customer
            GROUP BY CustomerID
        ) b ON  a.CustomerID = b.CustomerID AND
                a.purchasedate = b.maxDate