首页 > 解决方案 > 日期之间按周计数

问题描述

我试图按周显示计数,但我不确定如何找到 effdate 和 expdat 之间未显示的周。如何显示下面显示的星期和计数?谢谢。

在此处输入图像描述

标签: sqlsql-servertsqldategroup-by

解决方案


您可以使用递归查询来枚举周数,然后将其与表连接起来

with cte as (
    select min(effweek) week, max(expweek) max_week from mytable
    union all
    select week + 1, max_week from cte where week < max_week
)
select c.week, count(t.id_num) cnt
from cte c
left join mytable t on c.week between t.effweek and t.expweek
group by c.week
order by c.week

DB Fiddle 上的(简化)演示:

周 | cnt
---: | --:
  12 | 2
  13 | 1
  14 | 1

推荐阅读