简体   繁体   English

SQL 基于分组更新

[英]SQL Update based on grouping

Our system creates 2 lines per journal number and stamps a segment on each line.我们的系统为每个期刊编号创建 2 行,并在每行上标记一个段。

Line 1 is system generated and line 2 is what the user has entered front end.第 1 行是系统生成的,第 2 行是用户输入前端的内容。

The issue is the 2nd line of each journal the system populates the segment in the way the user entered it front end, where as the 1st line populates the segment how its stored in the back end - this means we can have case sensitive issues across the journal itself.问题是每个日志的第二行,系统以用户在前端输入的方式填充段,而第一行填充段是如何存储在后端的——这意味着我们可以在整个过程中遇到区分大小写的问题期刊本身。 Not an issue on the journal but causes issues further down the line.这不是期刊上的问题,但会导致进一步的问题。

Currently the table looks like below目前表格如下所示

HMY HMY Journal #杂志 # Segment部分
1 1个 10001 10001 House房子
2 2个 10001 10001 HouSE
3 3个 10002 10002 FLAT平坦的
4 4个 10002 10002 flat平坦的
5 5个 10003 10003 Unit单元
6 6个 10003 10003 UniT单元

The 2nd lines segment of each journal must be updated to match the segment on the 1st line.每个日志的第二行段必须更新以匹配第一行的段。

Desired end result:期望的最终结果:

HMY HMY Journal #杂志 # Segment部分
1 1个 10001 10001 House房子
2 2个 10001 10001 House房子
3 3个 10002 10002 FLAT平坦的
4 4个 10002 10002 FLAT平坦的
5 5个 10003 10003 Unit单元
6 6个 10003 10003 Unit单元

It has to update to how the system populated the segment so if it shows as all capitals, the 2nd line must be all capitals etc.它必须更新系统填充段的方式,因此如果它显示为所有大写字母,则第二行必须全部为大写字母等。

I have tried various methods but nothing is quite working how I would expect it.我尝试了各种方法,但没有一种方法能像我期望的那样有效。 For example I was trying to find the min(hmy) grouped by journal number and update the segment of the max(hmy) grouped by journal number but it wouldn't.例如,我试图找到按期刊编号分组的 min(hmy) 并更新按期刊编号分组的 max(hmy) 的段,但它不会。

Also looked at updating value based on previous row but could not work how I can incorporate that code into my issue.还查看了基于前一行的更新值,但无法解决如何将该代码合并到我的问题中的问题。

You can use LAG to get previous value and update:您可以使用 LAG 获取以前的值并更新:


update  t
set Segment = PrevSegment
FROM    (
    select  *
    ,   LAG(Segment) OVER(PARTITION BY [Journal #] ORDER BY HMY) AS prevSegment
    FROM    journaltable j
    ) t
WHERE   prevSegment IS NOT NULL -- prevents writing the system generated value

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

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