显示一个在另一个之上的值,而不是在属于同一行的同一行中

时间:2013-09-11 23:31:43

标签: sql sql-server rows

我有一行,其中两个不同的团队用他们的ID和名称替换。我想在下拉列表中显示它们。为此我需要以一个在另一个之上的格式显示它们。这是我的查询而Image是我得到的当前结果..

SELECT Match_Schedule.Match_Serno as 'Id', FirstHomeTeam.Serno as 'HomeTeamID', FirstHomeTeam.Team_Name as 'HomeTeam',SecondHomeTeam.Serno as 'AwayTeamID',SecondHomeTeam.Team_Name as 'AwayTeam'
 FROM Match_Schedule 
 INNER JOIN  Team_Detail AS FirstHomeTeam ON Match_Schedule.HomeTeam = FirstHomeTeam.Serno
 INNER JOIN Team_Detail AS SecondHomeTeam ON Match_Schedule.AwayTeam = SecondHomeTeam.Serno
 where Match_Serno=436

我得到的结果是enter image description here

但我想要的结果是。enter image description here

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以在UNPIVOT表格上执行Match_Schedule,然后JOINTeam_Detail表格来获取团队名称。

SELECT U.TeamID, TD.Team_Name
FROM Match_Schedule
UNPIVOT (TeamID FOR TeamName IN (HomeTeam, AwayTeam)) U
JOIN Team_Detail TD ON U.TeamID = TD.Serno
WHERE Match_Serno = 436

答案 1 :(得分:0)

您需要按摩数据以生成两行,然后使用外部查询查询这些行:

SELECT Id, TeamID
FROM (
    SELECT Serno as ID, Team_Name as TeamID, 'H' as TeamType 
    FROM Team_Detail 
    WHERE Serno = (SELECT HomeTeam FROM Match_Schedule WHERE Match_Serno = 436)
    UNION ALL
    SELECT Serno as ID, Team_Name as TeamID, 'A' as TeamType 
    FROM Team_Detail 
    WHERE Serno = (SELECT AwayTeam FROM Match_Schedule WHERE Match_Serno = 436)
)
ORDER BY TeamType DESC

答案 2 :(得分:0)

不需要花哨的UNPIVOT或子选择语句,以下内容将为您提供所需:

SELECT MS.Match_Serno AS 'Id', T.Serno AS 'TeamID', T.Team_Name AS 'TeamName'
FROM Match_Schedule MS
JOIN Team_Detail T
    ON MS.HomeTeam = T.Serno
    OR MS.AwayTeam = T.Serno
WHERE MS.Match_Serno = 436

如果您愿意,可以不使用第一列,我只是将其包含在内以供参考。