需要删除在标志值之前存在的行
我希望删除firstOrder
flag(由custome> customerId
)之前存在的行(以黄色突出显示)。
业务案例是我需要为每个在第一订单之前具有行的客户删除行(Asoftate)其中firstOrder = 1)。
我尝试创建另一列,以共融合每个客户的最低日期和每批的最低日期,以创建一种范围,但是我被困住的地方是如何考虑这些日期之间的无效。我的一个想法是将日期与第一个日期相同的日期之间的想法,然后我可以简单地删除该建议的“参考日期”&lt的行; (asofdate firstOrder = 1),但是我没有运气能够工作:
“ https://i.sstatic.net/djea2.png” alt =“在此处输入图像说明”>
我确定解决方案很简单而且我只是看不到它。这是示例数据:
CREATE TABLE #DATA (ASOFDATE DATE, CUSTOMERID INT, ACTIVE BIT, FIRSTORDER BIT)
INSERT INTO #DATA VALUES
('2018-01-31', 206424, NULL, NULL),
('2018-02-28', 206424, NULL, NULL),
('2018-03-31', 206424, 1, 1),
('2022-06-30', 206424, NULL, NULL),
('2022-07-31', 206424, NULL, NULL),
('2018-06-30', 247034, NULL, NULL),
('2018-07-31', 247034, NULL, NULL),
('2018-08-31', 247034, 1, 1),
('2022-05-31', 247034, NULL, NULL)
I am looking to remove the rows (highlighted in yellow) that exist prior to the FirstOrder
flag (partitioned by CustomerID
).
The business case is that I need to remove the rows for each customer that has a row before their First Order date (ASOFDATE where FirstOrder=1).
I have attempted the creation of another column that coalesces the minimum date per customer and the minimum date per FirstOrder, to create a kind of range, but where I was stymied was how to account for the NULL's in between those dates. The one idea I had was to make those in between dates the same as the first date, then I could simply remove rows where this proposed "reference date" < (asofdate where firstorder = 1), but I'm not having luck getting that to work:
I'm sure the solution is pretty simple and I'm just not seeing it. Here's the sample data:
CREATE TABLE #DATA (ASOFDATE DATE, CUSTOMERID INT, ACTIVE BIT, FIRSTORDER BIT)
INSERT INTO #DATA VALUES
('2018-01-31', 206424, NULL, NULL),
('2018-02-28', 206424, NULL, NULL),
('2018-03-31', 206424, 1, 1),
('2022-06-30', 206424, NULL, NULL),
('2022-07-31', 206424, NULL, NULL),
('2018-06-30', 247034, NULL, NULL),
('2018-07-31', 247034, NULL, NULL),
('2018-08-31', 247034, 1, 1),
('2022-05-31', 247034, NULL, NULL)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用条件总和()可以帮助
示例
更新表
Using a conditional sum() over() may help
Example
Updated Table
另一个工作选择是将表与“ firstorder ”的表选择匹配。然后,删除所有“ customerId ”的匹配行,该行比相应的“ asofdate ”低于相应的“ firstorder ”。
检查演示
Yet another working option is matching your table with a selection of your table where "FIRSTORDER" is true. Then remove all "CUSTOMERID" matching rows which have a lower "ASOFDATE" than the corresponding "FIRSTORDER".
Check the demo here.
尝试:
请参阅
”选择每个客户的第一个订单参考日期,然后使用该信息选择要删除的记录。
Try:
See This db<>fiddle
The CTE (common table expression) first picks the FIRSTORDER reference date for each customer, and the main query then uses that information to select the records to be deleted.