基于一列从表中删除重复行

时间:2013-01-06 15:41:50

标签: c# asp.net sql

我创建了一个包含4个表中多个内部联接的表,但结果会带回重复记录。这里是我正在使用的代码

SELECT   tblLoadStop.LoadID,
         tblCustomer.CustomerID,
         tblLoadMaster.BillingID,
         tblLoadMaster.LoadID,
         tblLoadMaster.PayBetween1,
         LoadStopID,
         tblLoadMaster.Paybetween2,
         tblStopLocation.StopLocationID,
         tblStopLocation.city,
         tblStopLocation.state,
         tblStopLocation.zipcode,
         tblLoadSpecifications.LoadID,
         tblLoadSpecifications.LoadSpecificationID,
         Picks,
         Stops,
         Typeofshipment,
         Weight,
         LoadSpecClass,
         Miles,
         CommodityList,
         OriginationCity,
         OriginationState,
         DestinationCity,
         DestinationState,
         LoadRate,
         Status,
         CompanyName,
         Customerflag,
         tblCustomer.CustomerID,
         tblCustomer.AddressLine1,
         tblCustomer.City,
         tblCustomer.State,
         tblCustomer.Zipcode,
         CompanyPhoneNumber,
         CompanyFaxNumber,
         SCAC,
         tblLoadMaster.Salesperson,
         Change,
         StopType
FROM     tblLoadMaster
            INNER JOIN tblLoadSpecifications 
                  ON tblLoadSpecifications.LoadID = tblLoadMaster.LoadID
            INNER JOIN tblLoadStop
                   ON tblLoadStop.LoadID = tblLoadMaster.LoadID
            INNER JOIN tblStopLocation
                   ON tblStopLocation.StopLocationID = tblLoadStop.StopLocationID
            INNER JOIN tblCustomer
                   ON tblCustomer.CustomerID = tblLoadMaster.CustomerID
WHERE    tblLoadMaster.Phase LIKE '%2%'
ORDER BY tblLoadMaster.LoadID DESC;

这是我得到的结果

Load ID   Customer   Salesperson     Origin  Destination     Rate    
-------------------------------------------------------------------------
13356     FedEx           Alex           Duluth    New York     300
13356     FedEx           Steve          Florida   Kansas       400

我只想显示第一行,

13356     FedEx           Alex           Duluth    New York     300

并删除底行

13356     FedEx           Steve          Florida   Kansas       400

tblLoadStop表具有来自tblloadMaster表的重复LoadID的重复记录

1 个答案:

答案 0 :(得分:2)

如果你使用的是SQL Server 2005及更新版本(在这方面你不够具体),一种方法是使用CTE(公用表表达式)。

使用此CTE,您可以按照某些条件对数据进行分区 - 即LoadID - 并为每个“分区”提供从1开始的所有行的SQL Server编号,按某些条件排序(您'不清楚如何你决定要保留哪一行以及在你的问题中忽略哪一行。

所以尝试这样的事情:

;WITH CTE AS
(
   SELECT 
       LoadID, Customer, Salesperson, Origin, Destination, Rate,
       RowNum = ROW_NUMBER() OVER(PARTITION BY LoadID ORDER BY tblLoadstopID ASC) 
   FROM 
       dbo.tblLoadMaster lm
     ......
   WHERE
      lm.Phase LIKE '%2%'
)
SELECT 
   LoadID, Customer, Salesperson, Origin, Destination, Rate
FROM 
   CTE
WHERE
   RowNum = 1

在这里,我只选择每个“分区”的“第一个”条目(即每个LoadId) - 按某些条件排序(更新:按{{1}排序} - 如你所述)你需要在你的CTE中定义。

这会接近你想要的吗?