在我的表MeterReading中,我有
-Id(Primary)
-ProjectMeterId
-MeterRead
-ReadDate
-ReadCount
我有一个给定ProjectMeterId的多个条目。我想只更新ReadDate最小的行的ReadCount(对于给定的ProjectMeterId),即
Update MeterReading
set ReadCount = 1234
where (ReadDate is minimun for a given ProjectMeterId)
注意:表中有许多ProjectMeterId,因此必须更新多个值。如何在查询中执行此操作,而不声明任何SP,声明表变量和所有??因此,更新所有条目需要10分钟以上。
这就是现在正在做的事情:
UPDATE TTable
SET TTable.ReadCount= 222
From
(
Select * From MeterReading where Id in
(
Select Id From
(
SELECT Min(Id)as Id, MIN(ReadDate) as ReadDate, ProjectMeterId FROM MeterReading
WHERE ProjectMeterId IS NOT NULL AND ProjectId IS NOT NULL Group By ProjectMeterId
) as temp1
)
) TTable,
(
Select * From MeterReading where Id in
(
Select Id From
(
SELECT MIN(ReadDate) as ReadDate, ProjectMeterId FROM MeterReading
WHERE ProjectMeterId IS NOT NULL AND ProjectId IS NOT NULL Group By ProjectMeterId
) as temp2
)
) STable
Where STable.ProjectMeterId = TTable.ProjectMeterId
但是subQueries中的Min(id)给了我那个具有ProjectMeterId特定的最小Id而不是ReadDate的行。
我该怎么办?
答案 0 :(得分:0)
;WITH CTE
AS (SELECT *,
MIN(ReadDate) OVER (PARTITION BY ProjectMeterId) AS Mn
FROM MeterReading)
UPDATE CTE
SET ReadCount = 1234
WHERE ReadDate = Mn
或者
UPDATE m1
SET ReadCount = 1234
FROM MeterReading m1
WHERE NOT EXISTS(SELECT *
FROM MeterReading m2
WHERE m1.ProjectMeterId = m2.ProjectMeterId
AND m2.ReadDate < m1.ReadDate)