1

我有一个表_1:

id  custno
1   1
2   2
3   3

和一个table_2:

id  custno  qty  descr
1   1       10   a
2   1       7    b
3   2       4    c
4   3       7    d
5   1       5    e
6   1       5    f

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

SELECT DISTINCT table_1.custno,table_2.qty,table_2.descr 
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  descr
1      5    e 
1      5    f
2      4    c
3      7    d

客户 1 每次以相同的最小数量出现两次(以及不同的描述),但我只想看到客户 1 出现一次。我不在乎这是以“e”作为描述还是以“f”作为描述的记录。

4

3 回答 3

3

首先...我不确定为什么您需要table_1在查询中包含以下内容:

select  custno, min(qty) as min_qty 
from    table_2 
group   by custno;

但以防万一您需要的其他信息未包含在问题中:

select table_1.custno, ifnull(min(qty),0) as min_qty
from   table_1 
       left outer join table_2 
          on table_1.custno = table_2.custno 
group  by table_1.custno;
于 2013-11-11T21:29:45.523 回答
1

“通用” SQL 方式:

SELECT table_1.custno,table_2.qty,table_2.descr 
FROM table_1, table_2 
WHERE table_2.id = (SELECT TOP 1 id 
                    FROM table_2 
                    WHERE custno = table_1.custno 
                    ORDER BY qty )

SQL 2008 方式(可能更快):

SELECT custno, qty, descr 
FROM
(SELECT 
    custno, 
    qty, 
    descr,
    ROW_NUMBER() OVER (PARTITION BY custno ORDER BY qty) RowNum
    FROM table_2
) A
WHERE RowNum = 1
于 2013-11-11T21:32:53.537 回答
0

如果你使用SQL-Server你可以使用ROW_NUMBERCTE

WITH CTE AS
(
    SELECT table_1.custno,table_2.qty,table_2.descr,
       RN = ROW_NUMBER() OVER ( PARTITION BY table_1.custno
                                Order By table_2.qty ASC)
    FROM table_1 
    LEFT OUTER JOIN table_2 
        ON  table_1.custno = table_2.custno 
)
SELECT custno, qty,descr
FROM CTE
WHERE RN = 1

Demolink

于 2013-11-11T21:33:07.963 回答