gpt4 book ai didi

SQL:如何用相同的值填充两个特定行之间的行?

转载 作者:行者123 更新时间:2023-12-02 09:23:22 26 4
gpt4 key购买 nike

我需要在两个“AL”或两个“MX”之间用“-”填充/替换行,其中值“AL”或“MX”取决于“-”出现的位置。出于本示例的目的,我仅使用 2 个“uid”(实际上我有更多 uid)。此外,该表按 ASC 中的 uid 和 code_date 列排序

为了便于理解,我有这个表格:

enter image description here

但我想要这样的东西:

enter image description here

我正在使用 SQL Server 2008。有关如何实现此目标的任何建议???

我使用以下代码创建了该表:

DECLARE @Customers TABLE
(uid bigint,
code_date date,
Value nchar(10)
)

INSERT INTO @Customers
VALUES (1591, '2016-08-01', ''),
(1591, '2016-08-02', ''),
(1591, '2016-08-03', 'AL'),
(1591, '2016-08-04', '-'),
(1591, '2016-08-05', '-'),
(1591, '2016-08-06', '-'),
(1591, '2016-08-07', '-'),
(1591, '2016-08-08', '-'),
(1591, '2016-08-09', 'AL'),
(1591, '2016-08-10', ''),
(1591, '2016-08-11', 'AL'),
(1591, '2016-08-12', ''),
(1082, '2016-02-01', ''),
(1082, '2016-02-02', ''),
(1082, '2016-02-03', ''),
(1082, '2016-02-04', ''),
(1082, '2016-02-05', 'MX'),
(1082, '2016-02-06', '-'),
(1082, '2016-02-07', '-'),
(1082, '2016-02-08', '-'),
(1082, '2016-02-09', '-'),
(1082, '2016-02-10', '-'),
(1082, '2016-02-11', '-'),
(1082, '2016-02-12', 'MX');

SELECT * FROM @Customers ORDER BY uid, code_date ASC

最佳答案

/* Test Data & Table */
DECLARE @Customers TABLE
(Dates datetime,
Customer integer,
Value integer)

INSERT INTO @Customers
VALUES ('20100101', 1, 12),
('20100101', 2, NULL),
('20100101', 3, 32),
('20100101', 4, 42),
('20100101', 5, 15),
('20100102', 1, NULL),
('20100102', 2, NULL),
('20100102', 3, 39),
('20100102', 4, NULL),
('20100102', 5, 16),
('20100103', 1, 13),
('20100103', 2, 24),
('20100103', 3, NULL),
('20100103', 4, NULL),
('20100103', 5, 21),
('20100104', 1, 14),
('20100104', 2, NULL),
('20100104', 3, NULL),
('20100104', 4, 65),
('20100104', 5, 23) ;

/* CustCTE - This gives us a RowNum to allow us to build the recursive CTE CleanCust */
WITH CustCTE
AS (SELECT Customer,
Value,
Dates,
ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY Dates) RowNum
FROM @Customers),

/* CleanCust - A recursive CTE. This runs down the list of values for each customer, checking the Value column, if it is null it gets the previous non NULL value.*/
CleanCust
AS (SELECT Customer,
ISNULL(Value, 0) Value, /* Ensure we start with no NULL values for each customer */
Dates,
RowNum
FROM CustCte cur
WHERE RowNum = 1
UNION ALL
SELECT Curr.Customer,
ISNULL(Curr.Value, prev.Value) Value,
Curr.Dates,
Curr.RowNum
FROM CustCte curr
INNER JOIN CleanCust prev ON curr.Customer = prev.Customer
AND curr.RowNum = prev.RowNum + 1)

/* Update the base table using the result set from the recursive CTE */
UPDATE trg
SET Value = src.Value
FROM @Customers trg
INNER JOIN CleanCust src ON trg.Customer = src.Customer
AND trg.Dates = src.Dates

/* Display the results */
SELECT * FROM @Customers

关于SQL:如何用相同的值填充两个特定行之间的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com