【问题标题】:SQL Server recursive CTE and pivot don't work togetherSQL Server 递归 CTE 和数据透视不能一起工作
【发布时间】:2012-09-24 20:50:48
【问题描述】:

为什么这个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,它会在 UPDATE 语句之后显示与 @tbl 中相同的值。

前段时间我花时间分析CTE + ROW_NUMBER(),但希望有人能解释一下。

【问题讨论】:

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


    【解决方案1】:

    我从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
    )
    

    然后我得到相同的结果。

    【讨论】:

    • 经典 PEBKAC。盯着它看了太久,它变成了星空……谢谢你的帮助。仅供参考,这里使用了该查询stackoverflow.com/a/12716649/573261,我以为我发现了另一个 CTE“功能”
    • @RichardTheKiwi - 很高兴我能帮上忙
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2014-05-19
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多