Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

sql server - SQL UPDATE statement does not update all rows in one execution

I have a table in MS SQL Server where the EXPECTED result should look like this: Table

Prior to expected result/query execution, all FieldX values are NULL. When I run my query, FieldX is only updated from row 2 to 8.

I need to UPDATE FieldX using a set of rules, which I define as such:

WITH cte_previous_rows AS (
    SELECT Date, Staff_Id, LAG(FieldX) OVER (partition by Staff_Id ORDER by [date]) as Prev_Row
FROM Sales 
) UPDATE Sales
SET FieldX = (CASE 
    WHEN Staff_id_sales < 1500 AND ClosedSale = 0 THEN 0
    WHEN Staff_id_sales = 1500 and ClosedSale = 0 THEN 5
    WHEN Staff_id_sales <= 3000 and Staff_id_sales > 1500 and ClosedSale = 0 THEN 1
    WHEN Staff_id_sales > 3000 and (c.Prev_Row = 1 OR c.Prev_Row = 0) THEN 2
    WHEN Staff_id_sales > 3000 and (c.Prev_Row = 2 or c.Prev_Row = 3) THEN 3 
    ELSE FieldX
END) 
FROM Sales
JOIN cte_previous_rows as c ON Sales.staff_id = c.staff_id AND Sales.Date = c.Date;

This query works just fine. But the problem lies in the last two WHEN statements. The reason for this, is of course that c.Prev_Row (previous row) is used in the rule set for these two last WHEN statements..

How can I edit my query so that the above rule set is applied on to all 50k rows in a SINGLE execution? Perhaps a new method is required..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A recursive CTE that works from the earliest row for each Staff_Id forward may be the ticket:

enter image description here

Note: This query was not run on an image of the data, so it might have some errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...