3

我有具有“x”行数的表 A。(对于这个例子有 8 行)

我通过使用游标创建具有“x”列数的Table-C 。(使这种动态化;如果向Table-A添加更多行,则在Table-C中创建更多列)

表 C(x = 1 到 8)
   用户 ID 1 2 3 4 5 6 7 8

创建Table-C后,根据从网页输入框传回的 userID 将行插入到Table-C中。(这是动态完成的)

插入后的表-C:
   用户 ID 1 2 3 4 5 6 7 8  
   57 null null null null null null null null  
   74 null null null null null null null null  

现在我希望执行 UPDATE
Table-B包含数据,其中列“x-column”将 UserID 关联到创建的Table-C中的列

表-B:  
用户 ID x 列  
34 2  
34 3  
57 2  
57 3  
57 8  
74 2  
74 4  
74 5  
74 7  
74 8  
93 2  
93 4  

所以最终结果是使用 1 动态更新Table-C,其中 Table-B.UserID = Table-C.column_heading

更新后的表 C 应如下所示:  
   用户 ID 1 2 3 4 5 6 7 8  
   57 空 1 1 空 空 空 1  
   74 空 1 空 1 1 空 1 1  

我很难弄清楚构建将处理此问题的 UPDATE 循环的语法。我需要使用游标吗?

我很确定这不是火箭科学,我还在学习!

4

1 回答 1

2

在没有看到您的整个过程的情况下,这是我关于如何执行此操作的建议。问题的一部分是结构,tablec要做到这一点,您首先要使用该UNPIVOT函数取消透视tablec并插入到临时表中:

select userid,
  value,
  col
into #temp
from tablec
unpivot
(
  value for col in ([1], [2], [3], [4], [5], [6], [7], [8])
) u

其次,使用以下方法更新临时表中的数据tableb

update t
set value = b.cnt
from #temp t
left join
(
  select count(x_column) cnt, x_column, userid
  from tableb
  group by x_column, userid
) b
  on t.userid = b.userid 
  and t.col = b.x_column

最后,使用该PIVOT函数将数据转换回您想要的格式:

select *
from
(
  select userid, value, col
  from #temp
) x
pivot
(
  max(value)
  for col in ([1], [2], [3], [4], [5], [6], [7], [8])
) p

请参阅SQL Fiddle with Demo

一些建议是看看你是否需要tablec在你现在的位置实际创建,如果不需要,那么你可以在执行时创建它PIVOT,那么数据就是你需要的最终结果。但是,您可以将数据保留为行格式,然后像我一样将其作为列返回。

如果要转换的列数未知,则可以使用动态 sql 执行此操作。

于 2012-10-23T20:27:06.160 回答