根据定义的条件从表中选择次数

时间:2020-08-28 21:26:16

标签: sql sql-server subquery union recursive-query

需要根据条件选择记录次数,因此需要选择每个ID的数量

示例:

ID |qty |column_A
1   13   12/31/2020
2   25   1/1/2021
3   34   1/2/2021
4   198  1/3/2021
5   97   1/4/2021

预期输出:

1
1
1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
...

注意:

qty=DATEDIFF(MONTH,'date',z.column A)+1 

1 个答案:

答案 0 :(得分:2)

一个选项使用递归查询。在标准SQL中,您可以这样写:

with recursive cte (id, qty) (
    select id, qty from mytable
    union all
    select id, qty - 1 from cte where qty > 0
)
select id from cte order by id
相关问题