SQL:仅比较日期与月份和年份列
我有一个表 MonthlyShipments
,如下所示:
partnumber | quantity | month | year |
part1 | 12 | 6 | 2011 |
part1 | 22 | 5 | 2011 |
part1 | 32 | 4 | 2011 |
part1 | 42 | 3 | 2011 |
part1 | 52 | 2 | 2011 |
我想对过去 3 个月的数量进行求和,不包括当月。我的 where 子句目前看起来像:
where
MonthlyShipments.Month <> MONTH(GETDATE()) AND
CAST(
(CAST(MonthlyShipments.Month as nvarchar(2)) +
'-01-' +
CAST(MonthlyShipments.Year as nvarchar(4))) as DateTime)
> DATEADD(m, -4, GETDATE())
它有效,但它丑陋且具有侮辱性。有什么建议可以让它变得更漂亮吗?非常感谢!
I have a table MonthlyShipments
that looks like:
partnumber | quantity | month | year |
part1 | 12 | 6 | 2011 |
part1 | 22 | 5 | 2011 |
part1 | 32 | 4 | 2011 |
part1 | 42 | 3 | 2011 |
part1 | 52 | 2 | 2011 |
I want to sum the quantities of the past 3 months, excluding the current month. My where clause currently looks like:
where
MonthlyShipments.Month <> MONTH(GETDATE()) AND
CAST(
(CAST(MonthlyShipments.Month as nvarchar(2)) +
'-01-' +
CAST(MonthlyShipments.Year as nvarchar(4))) as DateTime)
> DATEADD(m, -4, GETDATE())
It works, but its ugly and insulting. Any advice on making it prettier? Much appreciate!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好不了多少...
但是嵌套的 DATEADD 可以成为一个计算和索引列,
它给出
Not much better...
however the nested DATEADD can be made a computed and indexed column
which gives
可以添加日期栏吗?如果您需要进行日期计算并且您不希望事情变得丑陋,这可能是一个要求。即使计算列也可以工作......
然后你就可以做一些事情像这样:
Can you add a date column? If you need to do date calculations and you don't want things to get ugly this is probably going to be a requirement. Even a computed column would work...
Then you can just do something like this:
您可以将月份+日期转换为日期,然后将其与当前日期进行比较:
或者正如其他人所说,您可以创建一个包含日期类型的新计算列
You can convert your month+date to
date
and then compare it with current date:Or as it was said by others you can create a new computed column that holds
date
type如果你有一个
(year,month)
索引,我认为这会利用它:不过看起来不太漂亮。
If you have a
(year,month)
index, this will make use of it, I think:Not looking much prettier though.