我试图跟踪体育统计数据,我有两个表设置如下(团队将根据一周变化):
表1:
+---------+---------+---------+---------+
| Team | PYardG | RYardG | TDG |
+---------+---------+---------+---------+
| Steelers | 250 | 120 | 3 |
| Broncos | 200 | 130 | 2 |
+---------+---------+---------+---------+
表2:
+---------+---------+---------+---------+
| Week | Team1 | Team2 | Team3 |
+---------+---------+---------+---------+
| Week1 | Steelers | Broncos | Colts |
| Week2 | Patriots | Giants | Cowboys |
+---------+---------+---------+---------+
理想情况下,我的输出看起来像这样:
+---------+---------+---------+---------+
| Week1 | PYardG | RYardG | TDG |
+---------+---------+---------+---------+
| Steelers | 250 | 120 | 3 |
| Broncos | 200 | 130 | 2 |
+---------+---------+---------+---------+
目标是根据表2中的周和团队名称,按团队显示表1中的统计数据。
在进行一些研究时,我无法弄清楚子查询,JOIN或UNION是否是我最好的选择。有没有办法根据表2中的团队名称和周查找表1中的统计数据?我很感激帮助!
编辑:我为格式不佳的表道歉,这仍然是全新的。 编辑2:添加了所需的输出。表1将根据周而变化,我已经有一个脚本来按周存储我正在寻找的统计数据。答案 0 :(得分:0)
使用UNION
将Table2
中的所有团队放入子查询的单个列中。然后将其加入Table1
。
SELECT t1.team AS Week1, PYardG, RYardG, TDG
FROM Table1 AS t1
JOIN (SELECT Team1 AS team FROM Table2
WHERE week = 'Week1'
UNION
SELECT Team2 FROM Table2
WHERE week = 'Week1'
UNION
SELECT Team3 FROM Table2
WHERE week = 'Week1') AS t2
ON t1.team = t2.team
如果您对数据进行规范化,以便团队位于Table2
中的单独行中,而不是同一行中的多个列,则会更容易。然后你可以简单地与表连接,而不必将列旋转到子查询的行。
答案 1 :(得分:0)
我认为您需要更改表2的结构。 它可以像
+---------+---------+
| Week | Team |
+---------+---------+
| Week1 | Steelers |
| Week1 | Broncos |
| Week1 | Colts |
| Week2 | Patriots |
+---------+---------+
如果有超过三个团队,那么您需要每次都更改结构,这对数据完整性不利。
然后您可以使用简单的选择查询来获取数据。
从table1 t1,table2 t2选择t1.Team,t1.PYardG,t1.RYardG,t1.TDG,t2.week,其中week =' week1'和t1.team = t2.team;