使用MIN()左连接没有重复值

时间:2013-11-11 21:27:16

标签: sql sql-server sql-server-2008 tsql join

我有一个table_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'作为描述的记录。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

答案 2 :(得分: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