sql server查询如何与子查询进行多列比较

时间:2011-08-17 09:01:53

标签: sql sql-server-2008

如何根据子查询使更新查询正常工作? 如何将子查询中的所有这些列与update语句中的列进行比较? 有一些干净利落的方式吗?

我正在尝试的查询如下所示:

UPDATE Temp_CropData
SET RecordStatus = 0, 
    Remarks = ISNULL(Remarks, '') +' Duplicate Records' 
WHERE
     (SELECT Commodity ,City,Period,CropCondition
      FROM [Temp_CropData] 
      GROUP BY DDate,Commodity,City,Period,CropCondition 
      HAVING count(*) >1) 

2 个答案:

答案 0 :(得分:3)

尝试使用MERGE

MERGE INTO Temp_CropData
   USING (
          SELECT Commodity, City, Period, CropCondition
            FROM Temp_CropData
           GROUP 
              BY DDate, Commodity, City, Period, CropCondition 
          HAVING COUNT(*) > 1 
         ) AS source
      ON Temp_CropData.Commodity = source.Commodity 
         AND Temp_CropData.City = source.City
         AND Temp_CropData.Period = source.Period
         AND Temp_CropData.CropCondition = source.CropCondition
WHEN MATCHED THEN
   UPDATE
      SET RecordStatus = 0, 
          Remarks = ISNULL(Remarks, '') + ' Duplicate Records';

我有点怀疑您的子查询的SELECTGROUP BY条款不匹配(即DDate位于GROUP BY而不是SELECT {1}})。

答案 1 :(得分:1)

试试这个:

UPDATE cd
SET RecordStatus = 0,      
    Remarks = ISNULL(Remarks, '') +' Duplicate Records'  
FROM   Temp_CropData cd   
JOIN (SELECT Commodity ,City,Period,CropCondition       
FROM [Temp_CropData]        
GROUP BY DDate,Commodity,City,Period,CropCondition        
HAVING count(*) >1) dup 
    ON cd.DDate = dup.DDate AND cd.Commodity=dup.Commodity AND cd.City = dup.City 
    AND cd.Period = dup.Period AND cd.CropCondition = dup.CropCondition