sql—按时间段对数据进行分类

gt0wga4j  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(346)

我正在寻找一个sql语句来从表中选择所有时间段为今天、昨天等的行。table上有一个 datetime 列。
在这里,结果集应该自动填充结果与漂亮的日期(今天,昨天,。。上个月,旧)和期间的记录数,
今天——10
昨天——35

mwkjh3gx

mwkjh3gx1#

如果要定义时间段,请使用 case . 你并没有真正定义确切的定义,但是像这样:

select (case when col >= convert(date, getdate()) then 'Today'
             when col >= dateadd(day, -1, convert(date, getdate())) then 'Yesterday'
             when col >= dateadd(day, -6, convert(date, getdate())) then datename(weekday, col)
             when col >= dateadd(day, -13, convert(date, getdate())) then 'Last Week'
             when col >= dateadd(day, -20, convert(date, getdate())) then 'Two Weeks Ago'
             when col >= dateadd(day, -27, convert(date, getdate())) then 'Thre Weeks Ago'
             else 'Older'
        end)

这是一把小提琴。

相关问题