我需要在sql查询中获得帮助以获得此o / p

时间:2015-07-02 09:12:40

标签: sql sql-server-2008

我有一个表结构如下..

enter image description here

以下是样本数据......

tblTeam
----------------------------------
Name                                      TeamID
Royal Challengers Bangalore                 1
Chennai Super Kings                         2
Delhi Daredevils                            3
Sunrisers Hyderabad                         4
Kolkata Knight Riders                       5
Mumbai Indians                              6
Kings XI Punjab                             7
Rajasthan Royals                            8
Deccan Chargers                             9
Kochi Tuskers Kerala                       10
Pune Warriors                              11
------------------------------------------------

tblSchedule
------------------------------------------------
ScheduleID  DateTime    Team_1  Team_2  VenuID

1   4/18/08 8:00 PM 1   5   6
2   4/19/08 5:00 PM 2   7   9
3   4/19/08 8:30 PM 3   8   4
4   4/20/08 4:30 PM 5   9   1
5   4/20/08 8:00 PM 1   6   5
6   4/21/08 8:00 PM 8   7   27
7   4/22/08 8:00 PM 3   9   10
8   4/23/08 8:00 PM 2   6   2
9   4/24/08 8:00 PM 8   9   10
10  4/25/08 8:00 PM 6   7   9
11  4/26/08 4:00 PM 5   2   2
12  4/26/08 8:00 PM 1   8   6
-----------------------------------------------

pic中的黄色键表示主键,蓝色表示外键。

我的要求是这样的......

DateTime                 Team-1                 Team-2        
Apr 8, 2015 8:00:00 PM   Kolkata Knight Riders  Mumbai Indians

请帮助获得该o / p ......

2 个答案:

答案 0 :(得分:4)

使用不同的别名(T1和T2)加入elem.myProperty两次:

tblTeam

示例结果:

SELECT ScheduleID,DateTime,T1.Name as [Team-1],T2.Name as [Team-2]
FROM tblSchedule S JOIN
     tblTeam T1 ON S.Team_1=T1.TeamID JOIN 
     tblTeam T2 ON S.Team_2=T2.TeamID
ORDER BY S.ScheduleID

SQL Fiddle

中的示例结果

答案 1 :(得分:0)

我喜欢使用子查询来解决这类问题,以避免额外加入 产品

SELECT 
    CONVERT(varchar(20), DateTime, 100) AS DateTime, 
    (SELECT Name FROM tblTeam WHERE s.Team_1 = TeamID) AS Team-1, 
    (SELECT Name FROM tblTeam WHERE s.Team_2 = TeamID) AS Team-2 
FROM tblSchedule s

Extra reading