Need T-SQL help for converting Rows from multiple tables into Columns with values in Sql Server 2005

半世苍凉 提交于 2020-03-26 17:00:20

问题


I have a table tblUser:

tblUser

and a table tblBCE and data in the given below:

tblBCE

and a master table mstBCE which contains label text to display in front end application. This table contains data for other tab also but currently i want only for tabType 'BCE',I will do for other tab myself once i got the concept.

mstBCE

There is no relation between tblBCE and mstBCE tables,we need to follow the top to bottom sequence only.

In front end application i display these data only by sequence i.e.

i follow the sequence of both table to display data like for label "tab display text111111 BCE" comment value should be comments111111 and for label "tab display text222222 BCE" should be "comments22222" etc.

In front end it display as given below for one user:

so the output would be.

Output

Thanks


回答1:


My first thought is improve the schema and do you really need to do this.

To simplify the question it looks like you want to set the column name based on a join to mstBCE. You don't need a relation because the number of columns in tblBCE is fixed. Instead use dynamic sql to set the column names selecting from mstBCE pivoted onto one row.

DECLARE @sql nvarchar(4000); 
SELECT @sql = N'SELECT u.[username], u.[department], 
b.[Option1TB] as [' + pvt.[1] + N'], b.[Option1], 
b.[Option2TB] as [' + pvt.[2] + N'], b.[Option2], 
b.[Option3TB] as [' + pvt.[3] + N'], b.[Option3] 
FROM tblBCE as b 
JOIN tblUser as u ON b.[UserID] = u.[userid]; ' 
FROM (
    SELECT [tabconfigid], [tabdata] 
    FROM mstBCE 
    WHERE [tabType] = N'BCE'
) as m 
PIVOT ( MIN(m.[tabdata]) FOR m.[tabconfigid] IN ([1], [2], [3]) ) as pvt; 

EXEC (@sql); 


来源:https://stackoverflow.com/questions/9531771/need-t-sql-help-for-converting-rows-from-multiple-tables-into-columns-with-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!