[英]SQL query over two tables
I am having problems with queries: 我在查询时遇到问题:
My tables are following: 我的表如下:
Drivers 车手
|DRIVER_ID|FIRST_NAME|LAST_NAME|AGE|
| 1|John |Smith |19 |
| 2|Steve |Oak |33 |
| 3|Mary |Sanchez |22 |
Drivers_in_Teams 车手队
|DRIVERS_IN_TEAMS_ID|DRIVER_ID|TEAM_ID|BEG_DATE |END_DATE |
| 1| 1| 1|18-NOV-05| - |
| 2| 3| 2|10-APR-12| - |
| 3| 2| 3|19-JUL-01|02-AUG-04|
BEG_DATEs are done with "sysdate-number" BEG_DATE使用“ sysdate-number”完成
I would like to make one query, where it displays the oldest driver with first and last name, who is still in a team. 我想进行一个查询,在该查询中显示姓氏和名字最旧的驱动程序,而该驱动程序仍在团队中。
I tried some examples which I have found from google, but I can't get them to work. 我尝试了一些从google找到的示例,但无法使它们正常工作。 I'm beginner in SQL and I have no idea how to do this query.
我是SQL的新手,不知道如何执行此查询。
an example I found 我发现一个例子
SELECT FIRST_NAME, LAST_NAME
FROM DRIVER, DRIVERS_IN_TEAMS
WHERE DRIVER.DRIVER_ID = DRIVERS_IN_TEAMS.DRIVER_ID
AND DRIVERS_IN_TEAMS.BEG_DATE =
SELECT (SELECT MIN(BEG_DATE)
FROM DRIVERS_IN_TEAMS) (SELECT MAX(AGE)
FROM DRIVERS);
Try this: 尝试这个:
select top 1 first_name, last_name from Drivers as d
inner join Drivers_in_Teams as dit on d.driver_id = dit.driver_id
where isnull(end_date,'')=''
order by age desc
Comment if you have any questions or code doesn't work. 如果您有任何疑问或代码不起作用,请发表评论。
I think it should work. 我认为应该可以。 No resources to test and debug.
没有资源可以测试和调试。 Let me know if there are any problems.
让我知道是否有任何问题。
SELECT first_name FROM driver WHERE
driver_id in (select unique(driver_id) from driver_in_teams where end_date is NULL)
and age =(select MAX(age) from drivers)
Alternative: 选择:
SELECT first_name FROM driver d
INNER JOIN
driver_in_teams dt ON (d.driver_id=dt.driver_id)
WHERE dt.END_DATE IS NULL
AND d.age=(select MAX(age) from drivers)
SELECT FIRST_NAME, LAST_NAME, AGE
FROM Drivers
JOIN Drivers_in_Teams ON Drivers.DRIVER_ID = Drivers_in_Teams.DRIVER_ID
WHERE Drivers_in_Teams.END_DATE IS NULL
ORDER BY AGE DESC
This should join the two tables with the DRIVER_ID
on each, and then display only records that are NULL
, which I would assume is the '-' in your END_DATE
field. 这应该将两个表连接在一起,每个表上都有
DRIVER_ID
,然后仅显示NULL
记录,我认为这是您END_DATE
字段中的“-”。
This should do the trick: 这应该可以解决问题:
-- get the data you want
SELECT first_name, last_name, age FROM drivers d
WHERE d.age = (
-- get the max age from drivers still actives
SELECT MAX(age) FROM driver WHERE driver_id IN (
-- get drivers still active
SELECT drive_id FROM drivers_in_teams WHERE end_date IS NULL
) x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.