将组的最大值设置为每个组ID

时间:2016-02-09 11:23:34

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

这可能是一个愚蠢的问题而且很容易,但我现在非常分心,并没有找到任何解决方案。

我有一张这样的表:

ID | Value | Gr_Id | Gr_Value
------------------------------
a  |0      |1      |Null
b  |2      |2      |Null
c  |4      |2      |Null
d  |1      |3      |Null
e  |3      |4      |Null
f  |3      |4      |Null
g  |2      |5      |Null
h  |3      |5      |Null

期望的输出:

ID | Value | Gr_Id | Gr_Value
------------------------------
a  |0      |1      |0
b  |2      |2      |4
c  |4      |2      |4
d  |1      |3      |1
e  |3      |4      |3
f  |3      |4      |3
g  |2      |5      |3
h  |3      |5      |3

所以我想更新组值并设置group_id的最大值。 谢谢。

6 个答案:

答案 0 :(得分:1)

我认为这可以解决您的问题:

SELECT ID, Value, Gr_Id, (
           SELECT MAX(Value)
           FROM tableName t2 
           WHERE t1.Gr_Id = t2.Gr_Id
) as Gr_Value
FROM tableName t1

试试吧;希望它有所帮助

答案 1 :(得分:1)

使用SELECT ID,Value,Gr_Id,M.Gr_Value FROM URTable OUTER APPLY ( SELECT MAX (Value) as Gr_Value FROM URTable tmp WHERE tmp.Gr_Id=URTable.Gr_Id )M 可以执行此操作

{{1}}

答案 2 :(得分:1)

使用公用表表达式尝试此操作:

CREATE TABLE #t
(ID char,Value int, Gr_Id int, gr_value int)

INSERT #t(id, value, gr_id) 
values
('a',0,1),('b',2,2),('c',4,2),('d',1,3),
('e',3,4),('f',3,4),('g',2,5),('h',3,5)

;WITH CTE as
(
  SELECT 
    gr_value, 
    max(value) over(partition by gr_id) max_gr_value
  FROM #t
)
UPDATE CTE SET gr_value = max_gr_value

SELECT * FROM #t

结果:

ID   Value  Gr_Id  Gr_value
a    0      1      0
b    2      2      4
c    4      2      4
d    1      3      1
e    3      4      3
f    3      4      3
g    2      5      3
h    3      5      3

答案 3 :(得分:0)

这应该这样做:

UPDATE MyTable --whatever your table is called
SET Gr_Value = MaxValues.Value
FROM MyTable
INNER JOIN (
    SELECT Gr_Id, MAX(Value) AS Value
    FROM MyTable
    GROUP BY Gr_Id) AS MaxValues ON MaxValues.Gr_Id = MyTable.Gr_Id

答案 4 :(得分:0)

create table Gtable(ID varchar, Value int , Gr_Id int, Gr_Value int)
Insert into Gtable Values('a', 0, 1, null)
Insert into Gtable Values('b', 2, 2, null)
Insert into Gtable Values('c', 4, 2, null)
Insert into Gtable Values('d', 1, 3, null)
Insert into Gtable Values('e', 3, 4, null)
Insert into Gtable Values('f', 3, 4, null)
Insert into Gtable Values('g', 2, 5, null)
Insert into Gtable Values('h', 3, 5, null)

 select A.Id, A.Value, A.Gr_Id, C.maxV Gr_Value from Gtable A
JOIN 
    (   select A.Gr_Id, max(B.Value) maxV from
            ( select Distinct Gr_Id from Gtable ) A
                JOIN Gtable B On A.Gr_Id=B.Gr_Id 
                Group by A.Gr_Id
                ) C
                On A.Gr_Id=C.Gr_Id
Id  Value   Gr_Id   Gr_Value
a   0   1   0
b   2   2   4
c   4   2   4
d   1   3   1
e   3   4   3
f   3   4   3
g   2   5   3
h   3   5   3

答案 5 :(得分:0)

<强>查询

UPDATE t1
SET t1.Gr_Value = t2.val
FROM tblGroup t1
JOIN (SELECT Gr_Id, MAX(Value) AS val FROM tblGroup GROUP By Gr_Id) t2
ON t1.Gr_Id = t2.Gr_Id;