你可以使用一個union
包裹在一個distinct
子查詢:
select distinct A
, B
from (
select field1 as A, field11 as B from YourTable
union all
select field1, field12 from YourTable
union all
select field1, field13 from YourTable
union all
select field2, field21 from YourTable
union all
select field2, field22 from YourTable
) as SubQueryAlias
如果你的第一場總是6個charachters長,和你的第二個字段始終7,就可以產生這樣的查詢:
declare @sql varchar(max)
select @sql = case
when @sql is null then 'select ' + a.name + ' as a, ' + b.name +
' as b from TestTable '
else @sql + 'union all select ' + a.name + ', ' + b.name +
' from TestTable '
end
from sys.all_columns a
join sys.all_columns b
on len(b.name) = 7
and substring(b.name,1,6) = a.name
and b.object_id = a.object_id
where a.object_id = object_id('TestTable')
set @sql = 'select distinct a, b from (' + @sql + ') as SubQueryAlias'
exec (@sql)
您使用的是哪個版本的SQL Server? – 2011-02-26 08:56:11
sql server 2008 – jozi 2011-02-26 09:00:52