admin

使用MIN()进行左联接而没有重复值

sql

我有一张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”作为描述的记录。


阅读 198

收藏
2021-07-01

共1个答案

admin

“通用” 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
2021-07-01