Select 基于 select 查询中行的动态列

Select dynamic column based on rows in select query

数据结构如下

Table 1:

Col1a   Col1b   Col1c   Col1d
-----------------------------
 d11a    d11b    d11c    d11d
 d12a    d12b    d12c    d12d

Table 2:

Col2a   Col2b   Col2c   Col2d   Col2e
-----------------------------------
 s21a    s21b    s21c   Col1b   SUM(Col1b)
 s22a    s22b    s22c   Col1c   SUM(Col1c)
 s23a    s23b    s23c   Col1c   SUM(Col1c)
 s24a    s23b    s23c   Col1d   SUM(Col1d)

如你所见,我需要做什么。 目前 'Col2e' 是空的,我需要根据 'Col2d'.

中找到的单元格数据更新它

注:两者table都没有任何标识列。

我尝试使用函数在 select 查询中进行复制,但是它无法使用,因为它不能动态地用于 select 列。 我找不到 select/ 使用 Exec/ Exec sp_executesql.

进行更新的方法

如有任何建议,我们将不胜感激。

编辑: 我以后关注 table 可能会用于映射

Table ColumnMapping:

ColRowData  ColActualName   ColInTable
-----------------------------
 QTDCol  janQtd  Col1b
 FYCol   janFY   Col1c

这就是为什么我希望我的专栏 selections 是动态的。

这是你需要的吗?

select t2.*,
       (case when t2.col2d = 'Col1a' then sumcol1a
             when t2.col2d = 'Col1b' then sumcol1b
             when t2.col2d = 'Col1c' then sumcol1c
             when t2.col2d = 'Col1d' then sumcol1d
        end) as col2e
from table2 t2 cross join
     (select sum(col1a) as sumcol1a, sum(col1b) as col1b,
             sum(col1c) as sumcol1c, sum(col1d) as col1d
      from table1 t1
     ) t1;

如果我理解你的问题,下面的查询应该适合你。

update t2 
    set Col2e = (select case 
                        when t1.col1b = t2.col1b then Sum(col1b) 
                        when t1.col1c = t2.col1c then Sum(col1c) 
                        else Sum(col1d) 
                    end 
            from   table1 t1) 
from   table2 t2