想象一下以下3个表:
火车:钥匙,名称,出发日期
group_train:train,group
group:key,name
group_train.train作为train.key和group_train.group与group.key的外键关系。
一个小组可以包含多个列车,列车可能存在多个小组。
我想检索最新的火车到团队出发。基于train.departure_date
我已经尝试了多种类型的连接,子查询和分组子句。所有这些都没有成功。我似乎是一个简单的查询,但出于某种原因我被卡住了!
感谢您的帮助!
答案 0 :(得分:0)
尝试连接所有三个表并获取它的一个最新行输出,如:
SELECT g.key, g.name, MAX(t.departure_date)
FROM train t INNER JOIN group_train gt ON t.key = gt.train
INNER JOIN group g ON gt.group = g.key
GROUP by g.key, g.name
ORDER BY t.departure_date DESC
答案 1 :(得分:0)
试试这个:
SELECT g.key, g.name, t.key, t.name, t.departure_date
FROM group g
INNER JOIN group_train gt ON g.key = gt.group
INNER JOIN train t ON gt.train = t.key
INNER JOIN (SELECT gt.group, MAX(t.departure_date) AS departure_date
FROM group_train gt
INNER JOIN train t ON gt.train = t.name
GROUP BY gt.group
) AS A ON g.key = gt.group AND t.departure_date = A.departure_date;
答案 2 :(得分:0)
分析函数方法;
SELECT train.*
FROM
(
SELECT T.KEY,
T.NAME AS TRAIN_NAME,
T.departure_date,
G.name AS GROUP_NAME,
RANK() OVER (PARTITION BY G.group ORDER BY T.departure_date DESC) AS MY_RANK
FROM GROUP_TRAIN GT
INNER JOIN TRAIN T ON (GT.TRAIN = T.KEY)
INNER JOIN GROUP G ON (GT.group = G.group)
) train
WHERE MY_RANK = 1