(我已经多次询问过我的问题,涉及两个表格,并且已经回答here,here和here。但我无法弄清楚如何同样涉及三个表。)
我有三个表,A,B和C,其中A有很多B,B有很多C.我想加入这些表,每个A选择零行或一行,其中一个应该基于C中的条件
示例,假设:
@IBAction func btnLogin(sender: AnyObject) {
self.performSegueWithIdentifier("openSWL", sender: self)
}
...产生以下结果:
SELECT
a.aId
,b.bId
,c.cId
FROM
a
INNER JOIN b ON b.aId=a.aId
INNER JOIN c ON c.bId=b.bId
WHERE
c.someColumn='foo'
...然后我想要检索两个不同的A行,即aId bId cId
=== === ===
1 11 101
1 12 102
1 12 103
2 21 201
2 21 203
2 22 202
最高的行。
cId
答案 0 :(得分:6)
您可以使用ROW_NUMBER
:
WITH Cte AS (
SELECT
a.aId,
b.bId,
c.cId,
rn = ROW_NUMBER() OVER (PARTITION BY a.aId ORDER BY c.cId DESC)
FROM a
INNER JOIN b
ON b.aId = a.aId
INNER JOIN c
ON c.bId = b.bId
WHERE c.someColumn = 'foo'
)
SELECT
aId, bId, cId
FROM Cte
WHERE rn = 1