如何将列数据分配给其他表中的行

时间:2016-10-20 14:20:48

标签: sql sql-server

我想将一个表中的列数据分配给另一个表中的行 例如,考虑下面的两个表 表1具有以下结构(3列qid,问题,结果)和值

qid  question   result
1   question1   apple
1   question2   banana
1   question3   carrot
2   question1   mango
2   question2   orange
2   question3   popaya

表2具有以下结构(5列)和值

qid grade   test    question1   question2   question3
1    A     test1      NULL        NULL       NULL
2    B     test2      NULL        NULL       NULL

在表2中列为question1,question2,question3。我想根据qid分配结果列的值。

这是一种可能的情况吗?如果是的话,我该怎么做?

2 个答案:

答案 0 :(得分:0)

简单的答案是做这样的事情:

UPDATE table2
SET question1 = (select top 1 result from table1 t1 where t1.qid = qid AND question = 'question1'),
question2 = (select top 1 result from table1 t1 where t1.qid = qid AND question = 'question2'),
question3 = (select top 1 result from table1 t1 where t1.qid = qid AND question = 'question3')

注意:从数据库设计的角度来看,Table2并不理想。相反,你应该有这样的东西:

TABLE test
   - testID
   - testName
   - grade

TABLE question
   - testID
   - questionID
   - result

表格Test将所有问题都映射到同一个测试中,因此您不需要为问题1,问题2,问题3提供单独的列。毕竟,当你有200个问题进行测试时会发生什么?你想在你的table2中添加200列吗?

答案 1 :(得分:0)

稍微更改了查询。通过测试:

DECLARE @table TABLE
(
qid INT,
question NVARCHAR(30),
result NVARCHAR(30)
) 

DECLARE @table2 TABLE
(
qid INT,
grade NVARCHAR(2),
test NVARCHAR(10),
question1 NVARCHAR(20),
question2 NVARCHAR(20),
question3 NVARCHAR(20)
)

INSERT INTO @table
        ( qid, question, result )
VALUES  ( 1, -- qid - int
          N'question1', -- question - nvarchar(30)
          N'apple'  -- result - nvarchar(30)
          ),
        ( 1, -- qid - int
          N'question2', -- question - nvarchar(30)
          N'banana'  -- result - nvarchar(30)
          ),
        ( 1, -- qid - int
          N'question3', -- question - nvarchar(30)
          N'carrot'  -- result - nvarchar(30)
          ),
        ( 2, -- qid - int
          N'question1', -- question - nvarchar(30)
          N'mango'  -- result - nvarchar(30)
          ),
        ( 2, -- qid - int
          N'question2', -- question - nvarchar(30)
          N'orange'  -- result - nvarchar(30)
          ),
        ( 2, -- qid - int
          N'question3', -- question - nvarchar(30)
          N'popaya'  -- result - nvarchar(30)
          )

INSERT INTO @table2
        ( qid ,
          grade ,
          test
        )
VALUES  ( 1 , -- qid - int
          N'A' , -- grade - nvarchar(2)
          N'test1' -- test - nvarchar(10)
        ),
        ( 2 , -- qid - int
          N'B' , -- grade - nvarchar(2)
          N'test2' -- test - nvarchar(10)
        )

SELECT * FROM @table
SELECT * FROM @table2

这里是实际的声明:

UPDATE @table2 SET
question1 = (SELECT TOP 1 result FROM @table t WHERE t.qid = t2.qid AND question = N'question1'),
question2 = (SELECT TOP 1 result FROM @table t WHERE t.qid = t2.qid AND question = N'question2'),
question3 = (SELECT TOP 1 result FROM @table t WHERE t.qid = t2.qid AND question = N'question3')
FROM @table2 t2

结果:

SELECT * FROM @table2