消除查询中的重复记录

时间:2017-02-01 12:26:56

标签: sql-server tsql

那么如何消除重复记录?

select distinct top 10  Name, prd.productId, prd.SellStartDate,salesOrderID,
Name,ProductNumber,StandardCost,UnitPrice,OrderQty 
from SalesLT.Product as prd
INNER JOIN SalesLT.SalesOrderDetail as sale
on prd.ProductID=sale.ProductID
where 
prd.SellStartDate between '07/01/ 1998' and '01/01/2007'
and prd.ProductNumber is not null
and prd.Color in('Black','White')
order by prd.SellStartDate

enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个。

;WITH cte AS
    (
    select 
        Name
        , prd.productId
        , prd.SellStartDate
        , salesOrderID
        , Name
        , ProductNumber
        , StandardCost
        , UnitPrice
        , OrderQty 
        , RANK() OVER(PARTITION BY prd.SellStartDate ORDER BY salesOrderID) AS Rnk
    from 
        SalesLT.Product as prd
            INNER JOIN SalesLT.SalesOrderDetail as sale
                ON 
                prd.ProductID=sale.ProductID 
    WHERE 
        prd.SellStartDate between '07/01/1998' and '01/01/2007' 
        AND 
        prd.ProductNumber is not null 
        AND 
        prd.Color in('Black','White') 
    )
SELECT distinct top 10  
        Name
        , productId
        , SellStartDate
        , salesOrderID
        , Name
        , ProductNumber
        , StandardCost
        , UnitPrice
        , OrderQty 
FROM
    cte
WHERE rnk = 1
ORDER by 
    SellStartDate