根据组的最小值更新表的所有行

时间:2017-02-23 09:04:46

标签: sql sql-server sql-server-2008

我有一张这样的表

Date----- ----------Value--------- Group <br>
2017-01-01--------10--------------1--<br>
2017-01-02---------9---------------1--<br>
2017-01-03 --------5---------------2--<br>
2017-01-04 --------4---------------2--<br>

我想更新表格中的所有值列,以便将其设置为该组中的最小日期值

像这样

Date----- ----------Value--------- Group <br>
2017-01-01--------10--------------1--<br>
2017-01-02---------10---------------1--<br>
2017-01-03 --------5---------------2--<br>
2017-01-04 --------5---------------2--<br>

3 个答案:

答案 0 :(得分:0)

在这里,2个子查询,第一个计算每组的最小日期然后加入回原始表以获取相关值。然后最后将其连接到原始表以使用该值更新所有关联的组:

UPDATE M SET M.Value = RESULT.Value FROM MyTable M
 INNER JOIN (
  SELECT MV.Group, M.Value FROM MyTable M
     INNER JOIN (
         SELECT MIN(Date) as MinDateValue, Group FROM MyTable
         GROUP BY Group
           ) MV ON MV.MinDateValue = M.Date AND MV.Group = M.Group
  ) RESULT ON RESULT.Group = M.Group

答案 1 :(得分:0)

First get min date and value from sub query.Based on this result update main table

CREATE TABLE #Table(_Date Date,value INT,_Group INT)

INSERT INTO #Table(_Date ,value ,_Group)
SELECT '2017-01-01',10,1 UNION ALL
SELECT '2017-01-02',9,1 UNION ALL
SELECT '2017-01-03',5,2 UNION ALL
SELECT '2017-01-04',4,2

UPDATE #Table SET value = _Output._Value
FROM 
(
  SELECT A._Date , A._Group , T.value _Value
  FROM #Table T
  JOIN 
  (
    SELECT MIN(_Date) _Date ,_Group
    FROM #Table
    GROUP BY _Group
  ) A ON A._Date = T._Date

 ) _Output WHERE _Output._Group = #Table._Group

 SELECT * FROM #Table

答案 2 :(得分:0)

您还可以使用CTE

<强>查询

;with cte as(
    select [rn] = row_number() over(
        partition by [Group]
        order by [Date]
    ), *
    from [your_table_name]
)
update t1
set t1.[Value] = t2.[Value]
from cte t1
join cte t2
on t1.[Group] = t2.[Group]
and t1.[rn] > t2.[rn];