无法为下表编写SELECT查询

时间:2012-04-05 02:23:07

标签: sql ms-access

  

可能重复:
  Writing an SQL query to SELECT item from the following table

我正在尝试列出至少有两个不同部件的供应商的供应商名称(sname)和部件号(pnum)。

以下是我需要使用的两个表...

出货表: http://i44.tinypic.com/1zdcc9j.jpg

供应商表: http://i39.tinypic.com/o6w414.png

我尝试了什么:

这是不正确的,我沿着这些方向试了一下......

SELECT snum 
FROM (SELECT snum, count(snum) AS nbr FROM Shipments ) 
WHERE nbr > 1;

谢谢

3 个答案:

答案 0 :(得分:0)

SELECT suppliers.sname, shipments.pnum
FROM suppliers, shipments
WHERE shipments.snum = suppliers.snum
GROUP BY suppliers.sname
HAVING count(shipments.pnum) >= 2

答案 1 :(得分:0)

使用COUNT等聚合函数时,需要使用GROUP BY子句。使用Aggregates和GROUP BY时,HAVING CLAUSE充当您的where子句。

这将为您提供所有具有计数>的snums 1

SELECT snum
FROM
(
    SELECT snum, count(snum) AS nbr
    FROM Shipiments
    GROUP BY snum
    HAVING COUNT(snum) > 1
) AS T

这会将表格连接到供应商表格以获取供应商名称

SELECT DISTINCT Suppliers.sname
FROM
(
    SELECT snum, count(snum) AS nbr
    FROM Shipiments
    GROUP BY snum
    HAVING COUNT(snum) > 1
) AS T INNER JOIN Suppliers ON Suppliers.snum = T.snum

答案 2 :(得分:0)

我不知道Access(因为这个问题被标记为这样),但这应该适用于MySQL:

select su.sname from suppliers su
join shipments sh on su.snum = sh.snum
group by su.sname
having count(distinct su.pnum) >= 2