SQL选择MAX w / Left Join

时间:2014-02-19 22:38:47

标签: sql sql-server left-join

SELECT a.first, a.last, b.number, c.last_login
FROM Table1 a
LEFT JOIN Table2 b ON a.first = b.first AND a.last = b.last
LEFT JOIN Table3 c ON b.number = c.number

有时它们是数字的多个条目,我只需要从表b中选择最大数字,但是,当我尝试时

SELECT a.first, a.last, MAX(b.number), c.last_login

我收到错误。如何选择最大b.number?

2 个答案:

答案 0 :(得分:1)

编辑:很多年我没有完成SQLServer,但也许Analytic函数可以做到这一点

SELECT v.first, v.last, c.number, c.last_login
FROM (
    SELECT a.first, a.last, LAST_VALUE(b.number) OVER (PARTITION BY a.first, a.last ORDER BY a.first, a.last, b.number) AS yourmax
    FROM Table1 a
    LEFT JOIN Table2 b ON a.first = b.first AND a.last = b.last
    GROUP BY a.first, a.last
) v
INNER JOIN Table3 c ON v.yourmax = c.number

你能证实吗?我没有sqlserver,但在oracle上MAX()OVER(...)存在。 LAST_VALUE不是唯一适用于OVER analitics的关键字

答案 1 :(得分:0)

如果您想要最大数量,可以使用

SELECT a.first, a.last, b.MaxNumber, c.last_login
FROM Table1 a
LEFT JOIN (select tmp.first, tmp.last, max(tmp.number) MaxNumber from Table2 tmp
group by tmp.first, tmp.last
) b
ON a.first = b.first AND a.last = b.last
LEFT JOIN Table3 c ON b.MaxNumber = c.number