left join of with without duplicate records only showing 1 minimum value

送分小仙女□ 提交于 2019-12-13 03:59:46

问题


I have a table_1:

id  custno
1   1
2   2
3   3

and a table_2:

id  custno  qty
1   1       10 
2   1       7
3   2       4
4   3       7
5   1       5
6   1       5

When I run this query to show the minimum order quantities from every customer:

SELECT table_1.custno,table_2.qty 
FROM table_1 LEFT OUTER JOIN table_2 ON  table_1.custno = table_2.custno AND  
qty = (SELECT MIN(qty) FROM table_2  WHERE table_2.custno = table_1.custno   )

Then I get this result:

custno qty
1      5
1      5
2      4
3      7

How can I get the minimum value of qty per each custno?

How could I do this ?

Thx!


回答1:


What you mean is aggregation (GROUP BY):

SELECT table_1.custno,MIN(table_2.qty) AS [min_val]
FROM table_1 
LEFT OUTER JOIN table_2 ON  table_1.custno = table_2.custno 
GROUP BY table_1.custno



回答2:


SELECT table_2.custno, MIN(qty) as qty, descr
FROM table_2   
    LEFT OUTER JOIN table_1  
    on table_2.custno = table_1.custno 
GROUP BY table_2.custno, table_2.descr
ORDER BY table_2.custno

Note: the link to table_1, above, is only included on the assumption that you're either (1) using the JOIN to select rows in table_2 -- in other words, that table_2 has some custnos that are not present in table_1 -- or (2) that there are different values of the qty column for different values of your descr column (a column only mentioned in your comment, on another answer that was later deleted).

But if both tables have the same custnos, and the min(qty) for one descr is the same as the min(qty) for another, then the JOIN is unnecessary:

SELECT custno, MIN(qty) as qty, descr
FROM table_2   
GROUP BY custno, descr
ORDER BY custno


If, however, there are different MIN(qty) values for different descr column values, and you want to see all the descr values, but only one MIN(qty), (the MIN(qty) for all)... then you'd have to get creative... like JOINing twice so the columns can vary independently.
Here's a variation of Yosi's answer that would handle that:

SELECT table_1.custno, MIN(T2A.qty) AS [min_val], T2B.descr
FROM table_1 
LEFT OUTER JOIN table_2  T2A  ON  table_1.custno = T2A.custno 
LEFT OUTER JOIN table_2  T2B  ON  table_1.custno = T2B.custno 
GROUP BY table_1.custno, T2B.descr
ORDER BY table_1.custno


来源:https://stackoverflow.com/questions/19915849/left-join-of-with-without-duplicate-records-only-showing-1-minimum-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!