如何从加入排序获得前1名

时间:2017-08-20 07:07:57

标签: sql sql-server sql-server-2012

而不是做这样的事情:

SELECT
 t1.*,
 (SELECT TOP 1 t2.Name FROM Table2 t2 Order By t2.Number) Val1
FROM Table1 t1

如何使用Join来完成?

SELECT
  t1.*,
  TOP 1 t2.Name 
FROM Table1 t1
JOIN Table2 t2 Order By t2.Number

还是可能?

4 个答案:

答案 0 :(得分:0)

select  top 1 * from (SELECT t1.*, t2.Number num FROM table1 t1  JOIN table2 t2 on t1.commoncolumn=t2.commoncolumn ) t order by t.num

答案 1 :(得分:0)

试试这个(id是连接字段)

costeach({W, Q}) -> shop:cost(W)*Q.

答案 2 :(得分:0)

可以使用CROSS APPLY完成。假设Id是公共字段:

SELECT t1.*
  , t3.Name
FROM Table1 t1
CROSS APPLY (
  SELECT TOP 1 t2.Name
  FROM Table2 t2
  WHERE t1.Id = t2.Id
  ORDER BY t2.Number
) t3

答案 3 :(得分:0)

以下内容完成同样的事情。

SELECT t1.*, MIN(t2.Name) OVER() val1 FROM Table1 INNER JOIN Table2 t2 on t1.id = t2.id