当给定列值为零时,如何使用上面行中的值?
我有一个按日期排列的项目表(每行都是一个新日期)。我正在从另一列 D 中提取一个值。不过我需要它来替换 0。我需要以下逻辑:当该日期的 D=0 时,使用前一天 D 列中的值。
实际上,说实话,我需要说的是,当 D 为 0 时,使用 D 不为 0 的最新日期的值,但第一个将让我大部分顺利完成。
有没有办法建立这个逻辑?也许是 CTE?
非常感谢。
PS 我正在使用 SSMS 2008。
编辑:一开始我不太清楚。我要更改的值不是日期。我想根据日期将 D 中的值更改为 D 中最新的非零值。
I have a table of items by date (each row is a new date). I am drawing out a value from another column D. I need it to replace 0s though. I need the following logic: when D=0 for that date, use the value in column D from the date prior.
Actually, truth be told, I need it to say, when D is 0, use the value from the latest date where D was not a 0, but the first will get me most of the way there.
Is there a way to build this logic? Maybe a CTE?
Thank you very much.
PS I'm using SSMS 2008.
EDIT: I wasn't very clear at first. The value I want to change is not the date. I want change the value in D with the latest non-zero value from D, based on date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许以下查询可能对您有所帮助。它使用
OUTER APPLY
来获取结果。屏幕截图 #1 显示示例数据和针对示例数据的查询输出。这个查询可以写得更好,但这就是我现在能想到的。希望有帮助。
屏幕截图#1:
May be the following query might help you. It uses the
OUTER APPLY
to fetch the results. Screenshot #1 shows the sample data and query output against the sample data. This query can be written better but this is what I could come up with right now.Hope that helps.
Screenshot #1:
您可能可以将类似的内容作为更新脚本的一部分...
假设您想要实际更新数据,而不是仅仅出于选择查询的目的替换值。
You could maybe something like this as part of an update script...
That's assuming that you want to actually update the data though rather than just replace the values for the purpose of a select query.
怎么样:
How about:
或者如果你想完全避免聚合,
or if you want to avoid aggregates entirely,