0

我有一个表_1:

id  custno
1   1
2   2
3   3

和一个table_2:

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

当我运行此查询以显示每个客户的最小订单数量时:

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   )

然后我得到这个结果:

custno qty
1      5
1      5
2      4
3      7

如何获得qtyper each的最小值custno

我怎么能这样做?

谢谢!

4

2 回答 2

5

你的意思是聚合(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
于 2013-11-11T21:05:54.890 回答
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

注意:上面 table_1 的链接仅包含在以下假设(1)使用 JOIN选择table_2 中的行——换句话说,table_2 有一些在 table_1中不存在的 custnos——或(2)您的 desc 列的不同值(仅在您的评论中提到的列,在后来被删除的另一个答案上)有不同的 qty 列值。

但是,如果两个表具有相同的 custnos,并且一个描述的 min(qty) 与另一个描述的 min(qty) 相同,则不需要 JOIN:

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


但是,如果不同的 descr 列值有不同的 MIN(qty) 值,并且您想查看所有的 descr 值,但只有一个 MIN(qty),(所有的 MIN(qty))... 那么您'd 必须有创意......就像 JOINing 两次,所以列可以独立变化。
这是 Yosi 的答案的变体,可以解决这个问题:

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
于 2013-11-11T21:07:00.607 回答