sql - 按定义的条件从表中选择列的次数

标签 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 

最佳答案

一个选项使用递归查询。在标准 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

关于sql - 按定义的条件从表中选择列的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63641047/

相关文章:

mysql - SQL 仅选择列上具有最大值的行

php - 使用 PDO 语句未将数据插入 mysql

sql - sql中的字符串填充

MySql 子查询值未显示正确的结果

MySQL:引用子查询列

sql - 每年获得多项记录

MySQL错误: operand should contain 1 column(s) on simple update query

php - 如何将所有数组数据插入mysql?

c# - SQLBulkCopy 导致死锁

sql-server - 无法在 SQL Server Management Studio 中编辑 Azure 数据库的行