0

以下是我的查询。此查询返回图像中显示的以下结果集结果集 但我想要唯一的行。我怎样才能获得唯一的行?

Select
     distinct (tbl_Contract.ContractID),
     Tbl_Contract.KeyWinCountNumber,
     Tbl_Contract.ContractNumber,
     Tbl_Contract.ContractDate,
     Tbl_CountryFrom.CountryFromName,
     Tbl_CountryTo.CountryToName,
     tbl_Port.PortName,
     Tbl_Contract.Vans,
     Tbl_Contract.ContractID,
     Tbl_Item.ItemName,
     Tbl_Brand.BrandName,
     Tbl_Seller.SellerName,
     Tbl_Count.CountName,
     Tbl_Buyer.BuyerName

     from Tbl_Contract

     inner join Tbl_CountDetail
     on
     Tbl_CountDetail.ContractId = Tbl_Contract.ContractID
     inner join Tbl_Item
     on
     Tbl_Contract.ItemID = Tbl_Item.ItemID
     inner join Tbl_Brand
     on
     Tbl_Brand.BrandID = Tbl_Contract.ContractID
     inner join Tbl_Count
     on
     Tbl_CountDetail.CountId = Tbl_Count.CountID
     inner join Tbl_Seller 
     on
     Tbl_Seller.SellerID = Tbl_Contract.SellerID
     inner join Tbl_Buyer
     on
     Tbl_Buyer.BuyerID = Tbl_Contract.BuyerID
     inner join Tbl_CountryFrom
     on
     Tbl_CountryFrom.CountryFromID = Tbl_Contract.CountryFromID
     inner join Tbl_CountryTo
     on
     Tbl_CountryTo.CountryToID = Tbl_Contract.CountryToID
     inner join tbl_Port
     on
     tbl_Port.PortID = Tbl_Contract.PortID
4

1 回答 1

4

区别于ContractId?

您可以使用ROW_NUMBERPARTITION BY ContractId仅选择每个组中的第一个:

WITH CTE AS
(
    SELECT C.*,
      ROW_NUMBER() OVER (PARTITION BY ContractId Order By ContractDate DESC)AS RN
    FROM Tbl_Contract C
)
SELECT * FROM CTE WHERE RN = 1

请注意,您可以毫无问题地在 cte 中添加连接。为了提高可读性,我省略了它们。

于 2012-12-14T08:26:39.163 回答