gpt4 book ai didi

sql - 使用 CTE 拆分表中的行

转载 作者:行者123 更新时间:2023-12-02 08:44:49 29 4
gpt4 key购买 nike

我在 SQL Server 2008 R2 的表中有以下行

+-------------------------------------------+
| ID EntryType dt price |
+-------------------------------------------+
| 14 4 2012-11-07 0.025000 |
| 16 5 2012-11-07 0.026000 |
| 18 6 2012-11-07 0.026000 |
| 20 7 2012-11-07 0.026000 |
+-------------------------------------------+

我想做的是根据 EntryType 展开行(EntryType 不会改变)

For EntryType = 4 (1 row)
For EntryType = 5 (2 row)
For EntryType = 6 (3 row)
For EntryType = 7 (9 row)

并且 dt 字段将递增(以月为间隔),因此输出如下所示:

+-----------+-----------+-------+
| EntryType | dt | Price |
+-----------+-----------+-------+
| 4 | 11/7/2012 | 0.024 |
| 5 | 12/7/2012 | 0.025 |
| 5 | 1/7/2013 | 0.025 |
| 6 | 2/7/2013 | 0.026 |
| 6 | 3/7/2013 | 0.026 |
| 6 | 4/7/2013 | 0.026 |
| 7 | 5/7/2013 | 0.027 |
| 7 | 6/7/2013 | 0.027 |
| 7 | 7/7/2013 | 0.027 |
| 7 | 8/7/2013 | 0.027 |
| 7 | 9/7/2013 | 0.027 |
| 7 | 10/7/2013 | 0.027 |
| 7 | 11/7/2013 | 0.027 |
| 7 | 12/7/2013 | 0.027 |
| 7 | 1/7/2014 | 0.027 |
+-----------+-----------+-------+

是否可以使用 CTE 和 SQL 来做到这一点?

最佳答案

这是在 recursive CTE 中执行此操作的方法:

;with RecordCounts as (
-- Establish row counts for each EntryType
select 4 as EntryType, 1 as RecordCount
union all select 5, 2
union all select 6, 3
union all select 7, 9
), PricesCte as (
-- Get initial set of records
select ID, p.EntryType, (select min(dt) from MyTable) as dt, price, 1 as RecordNum
from MyTable p
join RecordCounts c on p.EntryType = c.EntryType -- Only get rows where we've established a RecordCount
-- Add records recursively according to RecordCount
union all
select ID, p.EntryType, dt, price, RecordNum + 1
from PricesCte p
join RecordCounts c on p.EntryType = c.EntryType
where RecordNum + 1 <= c.RecordCount
)
select EntryType,
dateadd(mm, row_number() over (order by EntryType, ID) - 1, dt) as dt,
price
from PricesCTE
order by EntryType
option (maxrecursion 0) -- Infinite recursion, default limit is 100

这是 SqlFiddle展示这项工作。

一些事情:

  • 我认为随着记录数量的增加,使用 Tally table 可能会表现更好而不是递归来增加记录。您将与 Tally 表交叉连接,并让 where 子句根据 RecordCount 限制记录
  • 我不明白定价从输入到输出应该如何变化。
  • 我不知道您在哪里为每个 EntryType 建立 RecordCount,所以我已将其添加到另一个 CTE 中。

关于sql - 使用 CTE 拆分表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271764/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com