可以在Query中写循环自动构造列。
直接分组构造列。
var
i: integer;
FieldList:String;
begin
FieldList := TStringList.Create;
try
//用临时的Query来取得所有的列;
with tempAdoQuerydo
begin
close;
Connection := //your's connection;
SQL.text := 'select * from table group a;
Open;
first;
FieldList := '';
for i:=0 to RecordCount-1do
begin
FieldList := FieldList+'(select * from table X'+inttostr(i)+" where X'+inttostr(i)+'.a = M.a) as ['+Trim(FieldByName('b').asString)+'],';
end;
//最后将逗号去掉;
FieldList := Copy(FieldList,1,Length(FieldList)-1);
end;
finally
fieldList.Free;
end;
//构造新的Query;
with AdoQuerydo
begin
Connection := //your connection;
Close;
Sql.text := Format('SELECT (select * from table X where X.a = M.a) as 类型,%S FROM table M',
[FieldList]);
Open;
end;
//最终看到的SQL语句是这样的:
//select (select * from table X where x.a = m.a) as 类型,
//(select * from table X1 where X1.a = M.a) as B1,......from table M
//前面的序号完全可以使用IDENTITY
//drop table #temptable
//select IDENTITY(int,1,1) as 序号,TABLE.* into #temptable from TABLE
//select * from #temptable