2

SQL-Server 2008で次のことを実行するためのコードが存在するかどうか疑問に思いましたか?

表1:

id    column name
-------------------
1     col1
2     col2
3     col3
4     col2

表2:

col1    col2    col3
--------------------
a       b       c

結果表:

id    data
--------------------
1     a
2     b
3     c
4     b

事前のおかげで、私は本当にこれを行う方法がわかりません。

4

3 に答える 3

2

UNPIVOT table2列からデータにアクセスするために使用できます。

select t1.id, t2.value
from table1 t1
left join 
(
  select value, col
  from table2
  unpivot
  (
    value
    for col in (col1, col2, col3)
  ) u
) t2
  on t1.name = t2.col

SQL FiddlewithDemoを参照してください

または、を使用して次UNION ALLのデータにアクセスできtable2ます。

select t1.id, t2.value
from table1 t1
left join 
(
  select col1 value, 'col1' col
  from table2
  union all
  select col2 value, 'col2' col
  from table2
  union all
  select col3 value, 'col3' col
  from table2
) t2
  on t1.name = t2.col

SQL FiddlewithDemoを参照してください

于 2012-09-21T16:07:54.857 に答える
0

私はあなたがそれらを列に接続せずにそれをどのように行うのかわかりません:

Table1:
ID
ColumnName

Table2:
Table1ID
Letter


Select table1.id, table2.Letter 
from table1 
inner join table2 on table1.ID = table2.Table1ID
于 2012-09-21T16:05:13.473 に答える
0

これは、caseステートメントとクロス結合を使用して実行できます。

select t1.id,
       (case when t1.columnname = 'col1' then t2.col1
             when t1.columnname = 'col2' then t2.col2
             when t1.columnname = 'col3' then t2.col3
        end) as data
from table1 t1 cross join
     table2 t2
于 2012-09-21T16:09:29.247 に答える