[英]sql-left-outer-join-with rows-based on column value from right table
[英]SQL left outer join to a min value of right table
我有兩個表,可以說table1
和table2
。
table1 || table2
--------||-------------
col1 || col1 | col2
--------||------|------
a || a | 4
b || a | 2
c || a | 5
d || b | 1
|| b | 3
|| d | 6
使用SELECT table1.col1, table2.col2 FROM table1 LEFT OUTER JOIN table2 ON table1.col1 = table2.col1
我得到以下信息:
table1.col1 | table2.col2
-------------|-------------
a | 4
a | 2
a | 5
b | 1
b | 3
c | NULL
d | 6
這怎么可能做到這一點(只得到最低的table2.col2
讓沒有進入table1.col1
不止一次):
table1.col1 | table2.col2
-------------|-------------
a | 2
b | 1
c | NULL
d | 6
還是錯誤的方法?
您需要使用MIN
:
SELECT
t1.col1,
MIN(t2.col2) AS col2
FROM table1 t1
LEFT JOIN table2 t2
ON t2.col1 = t1.col1
GROUP BY t1.col1
替代解決方案,使用相關子查詢:
select col1, (select min(col2) from table2 t2 where t2.col1 = t1.col1)
from table1 t1
如果table2
有更多列,則可能要使用APPLY
運算符:
SELECT * FROM table1
OUTER APPLY(SELECT TOP 1 * FROM table2
WHERE table1.col1 = table2.col1 ORDER BY table2.col2)oa
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.