如何选择列中的最小非重复值?

时间:2014-12-22 12:14:28

标签: sql sql-server duplicates

你能帮助我使用SQL语句来找到最小的非重复值吗? 这是我的sql语句

DECLARE @currentDate DATETIME = CONVERT(VARCHAR(10), Getdate(), 120)

UPDATE Dinfo
SET    WinnerID = result.CustomerID
FROM   Daily_Info Dinfo
       JOIN (SELECT CO.DailyInfoID,
                    CO.CustomerID
             FROM   Customer_Offer CO
             WHERE  CO.OfferDate = @currentDate
             GROUP  BY CO.DailyInfoID,
                       CO.CustomerID
             HAVING ( Count(CO.OfferPrice) = 1 )) result
         ON Dinfo.DailyID = result.DailyInfoID 

我希望更新提供最低独特优惠的获奖者。我该如何选择呢?

1 个答案:

答案 0 :(得分:0)

如果您想查找数据,那么我希望select。我认为以下查询可能会执行您想要的操作:

select min(offerprice)
from (select co.*, count(*) over (partition by co.offerprice) as cnt
      from Customer_Offer co
      where CO.OfferDate = @currentDate
     ) co
where cnt = 1;

如果您想根据此更新信息,请使用join

update dinfo 
    set winnerId = c.CustomerId
    from dinfo cross join
         (select top 1 co.*
          from (select co.*, count(*) over (partition by co.offerprice) as cnt
                from Customer_Offer co
                where CO.OfferDate = @currentDate
               ) co
          where cnt = 1
          order by offerprice
         ) c

这遵循查询的结构,但它将更新dinfo中的所有行。您可能需要一些其他条件,因此只更新了一行。