我有一个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”作为一个说明记录。
“通用” 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
首先,......我不知道为什么你需要包括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;
如果您使用SQL-Server
,你可以使用ROW_NUMBER
和CTE
:
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