简体   繁体   English

列的sql max基于行中的值

[英]sql max for column based on value in row

I am trying to get the maximum value in a column based on another value in a row. 我试图基于一行中的另一个值来获取一列中的最大值。

I have the following code : 我有以下代码:

    UPDATE LeweringVsSkattingResultaat
    SET maks = ((SELECT max(persentklaarkultivar2) FROM  
    LeweringVsSkattingResultaat) 
    group by kultivar2)

I get the following error :Incorrect syntax near the keyword 'group'. 我收到以下错误:关键字“ group”附近的语法不正确。

I want the maksimum value in column persentklaarkultivar2 for each value in kultivar2. 我想要persentklaarkultivar2列中的kaksimum值用于kultivar2中的每个值。

Any help would be much appreciated. 任何帮助将非常感激。

Regards 问候

Your subquery would generate an error if you have more than on value for kultivar2 . 如果kultivar2值大于on,则子查询将生成错误。 The group by would return a row for each kultivar2 . group by将为每个kultivar2返回一行。

Although you can use a correlated subquery to fix the problem (see end of answer), I like to do this with updatable CTEs and window functions: 尽管您可以使用相关的子查询来解决问题(请参见答案结尾),但我还是喜欢使用可更新的CTE和窗口函数来做到这一点:

with toupdate as (
      select r.*,
             max(persentklaarkultivar2) over (partition by kultivar2) as maxval
      from LeweringVsSkattingResultaat r
     )
update toupdate
     set maks = maxval;

I should note that with window functions, you can readily calculate the maximum whenever you want, so it is not necessary to store it. 我应该注意,使用窗口函数,您可以随时随地轻松计算最大值,因此没有必要进行存储。 Window functions are optimized so they can take advantage of an index on LeweringVsSkattingResultaat(kultivar2, persentklaarkultivar2) . 窗口函数已经过优化,因此它们可以利用LeweringVsSkattingResultaat(kultivar2, persentklaarkultivar2)上的索引。

This is probably a better approach. 这可能是更好的方法。 You won't have to figure out how to keep the maks value up-to-date when rows are inserted, updated, or deleted from the table. 当您在表中插入,更新或删除行时,您将不必弄清楚如何使maks值保持最新。

The correlated subquery would look like: 相关的子查询如下所示:

UPDATE r
    SET maks = (SELECT max(r2.persentklaarkultivar2)
                FROM LeweringVsSkattingResultaat r2 
                WHERE r2.kultivar2 = r.kultivar2
               )
    FROM LeweringVsSkattingResultaat r;

Remove a () 删除()

 UPDATE LeweringVsSkattingResultaat
    SET maks = ( SELECT max(persentklaarkultivar2) FROM  
    LeweringVsSkattingResultaat 
    group by kultivar2)

otherwise your group by is out the inner select 否则,您的分组依据不在内部选择之列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM