问题描述
我需要将出现在不同表中的列标题显示为列表。
示例:
Column headings - Adam,Cory,Jack,Jane,John,Josef,Mary,Timothy,Charlotte,Jessica,Kristal,Clive
Required column headings (contained within another table) - Jack,Maria,Josef
如何检查列标题是否与“必需”列表中的列标题相等,然后仅显示那些标题?
解决方法
我建议您使用数据透视和动态SQL。从您的完整名称表连接到所需的名称表,最后仅得到您需要的名称作为列。格式化这些值,以便以后与动态SQL结合使用。使用数据透视,您不得不聚集一些东西。有关更多信息,请参见无汇总发布的“将数据透视表的行转换为列”。我将1硬编码为我们需要调整的合计值。您可以忽略该值,并以名称联接(假设这是您通往其他表的键)以获取每个名称的其他数据。
https://docs.microsoft.com/en-us/sql/odbc/reference/dynamic-sql?view=sql-server-ver15
Pivot rows to columns without aggregate
declare @PivotColumns nvarchar(max) = ''
create table #required ( name nvarchar(500) )
insert into #required ([name])
select 'Jack' union select 'Jane' union select 'John' union select 'Mary' union select 'Maria' union select 'Josef'
create table #allnames ( name nvarchar(500) )
insert into #allnames ([name])
select 'Adam' union select 'Cory' union select 'Jack' union select 'Jane' union select 'John' union select 'Josef' union select 'Mary' union select 'Timothy' union select 'Charlotte' union select 'Jessica' union select 'Kristal' union select 'Clive' union select 'Maria'
select @PivotColumns = @PivotColumns + QUOTENAME([name]) + ',' from #required
select @PivotColumns = substring(@PivotColumns,1,len(@PivotColumns)-1)
declare @SQL nvarchar(max) = ''
select @SQL = N'
select
*
from (
select
req.*,1 [Val]
from #allnames as [All]
join #required as Req
on [All].[name] = Req.[name]
) src
pivot
(
max([Val])
FOR [name] in ('+@PivotColumns+')
) piv';
exec sp_executesql @SQL
drop table #required
drop table #allnames