sql-server - SQL Server 递归 CTE 和数据透视不能一起工作

标签 sql-server tsql pivot common-table-expression recursive-query

这为什么不SQL Fiddle工作?

复制完整脚本:

create table tbl (
  id int,
  month varchar(9),
  value float);
insert tbl values
(1,'Jan',0.12),
(1,'Feb',0.36),
(1,'Mar',0.72),
(2,'Mar',0.11),
(2,'Apr',0.12),
(2,'May',0.36);

declare @tbl table (
  id int,
  number int,
  month varchar(9),
  value float);
insert @tbl
select id.id, Months.Number, Months.Name, t.value
from (values(1,'Jan'),
            (2,'Feb'),
            (3,'Mar'),
            (4,'Apr'),
            (5,'May'),
            (6,'Jun')) Months(Number,Name)
cross join (select distinct id from tbl) id
left join tbl t on t.month = Months.name and t.id=id.id;

;with cte as (
  select id,Number,month,isnull(Value,0.0)value
  from @tbl
  where Number=1
  union all
  select cte.id,cte.Number+1,cte.month,isnull(t.value,cte.Value)
  from cte
  join @tbl t on t.id=cte.id and t.number=cte.number+1
)
/*update t
set value=cte.value
from @tbl t
join cte on t.id=cte.id and t.number=cte.number;*/

select id, Jan,Feb,Mar,Apr,May,Jun
from (select id,month,value from /*@tbl*/ cte) p
pivot (max(value) for month in (Jan,Feb,Mar,Apr,May,Jun)) v;

预期结果:
ID  JAN FEB MAR APR MAY JUN
1   0.12    0.36    0.72    0.72    0.72    0.72
2   0   0   0.11    0.12    0.36    0.36

实际结果:
ID  JAN FEB MAR APR MAY JUN
1   0.72    (null)  (null)  (null)  (null)  (null)
2   0.36    (null)  (null)  (null)  (null)  (null)

如果您取消注释注释掉的代码,它就可以工作。但是,如果您直接从 CTE 中选择 SELECT * FROM CTE ,它显示的值与 @tbl 中的值相同在 UPDATE 语句之后。

我花时间分析CTE + ROW_NUMBER()不久前,但希望有人能解释这一点。

最佳答案

我没有从 CTE 得到相同的结果我从 @tbl 得到的.对于 CTE所有月份都是JAN .如果你用这个改变你的 CTE 定义:

;with cte as (
  select id,Number,month,isnull(Value,0.0)value
  from @tbl
  where Number=1
  union all
  select cte.id,cte.Number+1,t.month /*here there was cte.month*/,
         isnull(t.value,cte.Value) 
  from cte
  join @tbl t on t.id=cte.id and t.number=cte.number+1
)

然后我得到相同的结果。

关于sql-server - SQL Server 递归 CTE 和数据透视不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12716753/

相关文章:

ruby-on-rails - Rails、二维表、pivot、嵌套散列循环

SQL 按两列对项目进行计数和分组

mysql - 获取每个用户得分最高的帖子

python - 如何通过 pyodbc 在 MS SQL 服务器上的 2 个表上放置范围/表锁

SQL 公式返回不一致的精度

mysql - 如何在单行中计数?

c# - 使用 SMO 更改 SQL Server 数据库默认位置

sql - 查询从 SQL Server 中的表中检索前两行

SQL Server : loop through every row, 向列添加增量值

mysql - 是否可以在 MySQL 中使用交叉表/数据透视查询?