是否有更有效的方法从同一个 table 追加多个列?

Is there a more efficient way to append multiple columns from the same table?

我想 return 来自同一条记录的多个值,同一类型的不同列相互追加。我可以进行多次连接,但由于多次 table 扫描,这似乎效率很低。

declare @gameID as VarChar(30)
select @gameID = '20210829-SLNvsPIT-0'

select Vis1ID as VisID, Vis1 as Vis, Home1 as Home, Home1ID as HomeID
from Baseball.dbo.GameLogs
where GameID = @gameID
union
select Vis2ID, Vis2, Home2, Home2ID
from Baseball.dbo.GameLogs
where GameID = @gameID
union
.......
select Vis9ID, Vis9, Home9, Home9ID
from Baseball.dbo.GameLogs
where GameID = @gameID

Returns:

VisID Vis Home HomeID
arenn001 Nolan Arenado Colin Moran morac001
badeh001 Harrison Bader Anthony Alford alfoa002
carld002 Dylan Carlson Yoshi Tsutsugo tsuty001
edmat001 Tommy Edman Kevin Newman newmk001
goldp001 Paul Goldschmidt Ke'Bryan Hayes hayek001
kim-k001 Kwang Kim Wil Crowe croww001
moliy001 Yadier Molina Jacob Stallings stalj001
oneit001 Tyler O'Neill Bryan Reynolds reynb001
sosae001 Edmundo Sosa Cole Tucker tuckc001

这正是我要找的东西,但速度太慢了。有没有更好的方法?

您需要对每一行进行逆透视。这意味着您只扫描 table 一次,然后将其分成单独的行。您可以使用 UNPIVOT,但 CROSS APPLY (VALUES 更灵活。

DECLARE @gameID varchar(30) = '20210829-SLNvsPIT-0';

SELECT
  v.VisID,
  v.Vis,
  v.Home,
  v.HomeID
FROM dbo.GameLogs gl
CROSS APPLY (VALUES
    (Vis1ID, Vis1, Home1, Home1ID),
    (Vis2ID, Vis2, Home2, Home2ID),
    (Vis3ID, Vis3, Home3, Home3ID),
    (Vis4ID, Vis4, Home4, Home4ID) -- .....
) v(VisID, Vis, Home, HomeID)
WHERE gl.GameID = @gameID;

不言而喻,您的 table 严重反规范化,应该立即重新设计。