根据表的日期自动递增表中的 id 数据

问题描述 投票:0回答:1

我有下表

create table summry(
  id  varchar(12),
  Desc varchar(50),
  Qty decimal(25),
  code varchar(20),
  Date int,
  Days int)

天数是根据该 ID 的日期和代码计算的。
例如:如果 id-294 code-123 的日期为 16/1,则天数为 1
如果相同的 id-294 和代码 123 的日期为 17/1,则天数为 2,然后是第二个条目

如何为此更新编写 SQL 查询?

插入摘要(id,代码,日期,天)值(294,123,'12/1/24',1)

数据:

身份证 代码 日期
294 123 12/1/24 1
294 123 13/1/25 1
294 123 15/1/25 1
294 123 16/1/25 1
294 123 17/1/25 1

预计:

身份证 代码 日期
294 123 12/1/25 1
294 123 13/1/25 2
294 123 15/1/25 1
294 123 16/1/25 2
294 123 17/1/25 3

自 14 日起,不再是 der,因此天数计算再次从 1 开始。所以天数主要是根据特定 Id 和代码的日期计算的

sql mysql
1个回答
0
投票
I think below sql code will give you the expected result. please try it:

WITH RankedData AS (
    SELECT
        id,
        code,
        date,
        ROW_NUMBER() OVER (PARTITION BY id, code ORDER BY date) AS rn
    FROM
        summary
),
DateDifferences AS (
    SELECT
        id,
        code,
        date,
        rn,
        DATEADD(DAY, -rn, CAST(date AS DATE)) AS group_identifier
    FROM
        RankedData
),
GroupedData AS (
    SELECT
        id,
        code,
        date,
        DENSE_RANK() OVER (PARTITION BY id, code ORDER BY group_identifier) AS group_number
    FROM
        DateDifferences
),
FinalDaysCalculation AS (
    SELECT
        id,
        code,
        date,
        ROW_NUMBER() OVER (PARTITION BY id, code, group_number ORDER BY date) AS days
    FROM
        GroupedData
)
UPDATE summary
SET days = f.days
FROM FinalDaysCalculation f
WHERE summary.id = f.id
  AND summary.code = f.code
  AND summary.date = f.date;
© www.soinside.com 2019 - 2024. All rights reserved.