使用滞后函数从 select(子查询)更新
Update from select (subquery) using lag function
我正在 SSMS 中进行更新查询,以计算具有匹配序列号的两个不同行之间的天数。目标是按序列号进行分区,然后查看滞后记录并计算两条记录之间的天数。作为 select 查询,我填充了正确的信息。尝试使用 select 部分作为子查询将记录更新到 table 中时出现错误,以便我可以将这些值导入另一个系统以构建数据可视化。感谢您的帮助!
UPDATE qa_combined_data2
SET
qa_combined_data2.days_since_last_return =
(SELECT serial_number,
receive_date,
datediff(day, receive_date, LAG(receive_date, 1)
OVER (PARTITION BY serial_number
ORDER BY receive_date)) *-1
AS days_between_returns_update
FROM qa_combined_data2)
WHERE qa_combined_data2.serial_number = qa_combined_data2.serial_number
AND qa_combined_data2.receive_date = qa_combined_data2.receive_date;
尝试这样的事情:
UPDATE Q1
SET days_since_last_return = Q2.days_between_returns_update
FROM qa_combined_data2 Q1
INNER JOIN
(SELECT serial_number,
receive_date,
datediff(day, receive_date, LAG(receive_date, 1)
OVER (PARTITION BY serial_number
ORDER BY receive_date)) *-1
AS days_between_returns_update
FROM qa_combined_data2) Q2
ON Q1.serial_number = Q2.serial_number
AND Q1.receive_date = Q2.receive_date;
您的主要问题是您在子查询中选择了额外的列。此外,您的 WHERE
没有任何意义,可能应该在子查询的内部。
另一个问题是您不需要子查询和 re-querying 基础 table。您可以使用派生的 table 或 CTE,只需查询基础 table 一次。
还有:
* -1
等同于 -
.
- 但无论如何您都不需要它,因为您可以交换
LAG
参数。
LAG(..., 1)
是默认值。
UPDATE qad
SET
days_since_last_return = days_between_returns_update
FROM (
SELECT *,
DATEDIFF(day, LAG(receive_date)
OVER (PARTITION BY serial_number
ORDER BY receive_date)
, receive_date)
AS days_between_returns_update
FROM qa_combined_data2
) qad;
我正在 SSMS 中进行更新查询,以计算具有匹配序列号的两个不同行之间的天数。目标是按序列号进行分区,然后查看滞后记录并计算两条记录之间的天数。作为 select 查询,我填充了正确的信息。尝试使用 select 部分作为子查询将记录更新到 table 中时出现错误,以便我可以将这些值导入另一个系统以构建数据可视化。感谢您的帮助!
UPDATE qa_combined_data2
SET
qa_combined_data2.days_since_last_return =
(SELECT serial_number,
receive_date,
datediff(day, receive_date, LAG(receive_date, 1)
OVER (PARTITION BY serial_number
ORDER BY receive_date)) *-1
AS days_between_returns_update
FROM qa_combined_data2)
WHERE qa_combined_data2.serial_number = qa_combined_data2.serial_number
AND qa_combined_data2.receive_date = qa_combined_data2.receive_date;
尝试这样的事情:
UPDATE Q1
SET days_since_last_return = Q2.days_between_returns_update
FROM qa_combined_data2 Q1
INNER JOIN
(SELECT serial_number,
receive_date,
datediff(day, receive_date, LAG(receive_date, 1)
OVER (PARTITION BY serial_number
ORDER BY receive_date)) *-1
AS days_between_returns_update
FROM qa_combined_data2) Q2
ON Q1.serial_number = Q2.serial_number
AND Q1.receive_date = Q2.receive_date;
您的主要问题是您在子查询中选择了额外的列。此外,您的 WHERE
没有任何意义,可能应该在子查询的内部。
另一个问题是您不需要子查询和 re-querying 基础 table。您可以使用派生的 table 或 CTE,只需查询基础 table 一次。
还有:
* -1
等同于-
.- 但无论如何您都不需要它,因为您可以交换
LAG
参数。 LAG(..., 1)
是默认值。
UPDATE qad
SET
days_since_last_return = days_between_returns_update
FROM (
SELECT *,
DATEDIFF(day, LAG(receive_date)
OVER (PARTITION BY serial_number
ORDER BY receive_date)
, receive_date)
AS days_between_returns_update
FROM qa_combined_data2
) qad;