我有两张桌子:
TABLE_1
No.
----------
Question01
Question02
...
QuestionN
TABLE_2
No. | Questions
----------
Question01 Favourite Colour?
Question02 Favourite Food?
...
QuestionN Favourite Song?
我希望得到一个看起来像这样的结果:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
我需要结果表是动态的,因为问题的数量可能会有所不同 有谁知道我会怎么做呢?
答案 0 :(得分:0)
您可以使用动态sql和unpivot:
DECLARE @sql NVARCHAR(max)
DECLARE @column_list NVARCHAR(max) = N''
SELECT @column_list += QUOTENAME(q) + ',' FROM Table_2
SET @column_list = SUBSTRING(@column_list, 1, LEN(@column_list) -1)
SET @sql = CONCAT(N'
SELECT up.[No.], up.[Questions] FROM (
SELECT
',@column_list,N'
FROM Table_1
) p
UNPIVOT ([No.] FOR [Questions] IN (',@column_list,N')) AS up')
PRINT @sql
EXEC (@sql)