【问题标题】:SQL select records if the sum is grater than or equal to two如果总和大于或等于 2,则 SQL 选择记录
【发布时间】:2020-09-01 16:06:05
【问题描述】:

我想显示公司名称和公司供应的产品数量,只要产品数量超过两个即可。

以下是供应商表的摘录:

SupplierID    CompanyName       . . . 
1             Exotic Liquids
2             New Orleans Cajun 
3             Grandma Kelly's   
.
.

这是 Products 表的摘录:

ProductId   ProductName      SupplierID  CategoryID .  .
1           Chai             1           1
2           Chang            1           1
3           Aniseed Syrup    1           2
4           Cajun Seasoning  2           2
5           Gumbo Mix        2           2
6           Berry Spread     3           2
.
.

我使用的SQL代码:

SELECT   S.CompanyName , (SUM(P.SupplierID)) AS 'Number of Products'
FROM     Suppliers S, Products P
WHERE    P.SupplierID = S.SupplierID
GROUP BY S.CompanyName
ORDER BY SUM(P.SupplierID) >= 3

使用上面的代码,MSSQL 服务器给了我一个Incorrect syntax near '>' 错误。 我不知道如何解决这个问题以获得如下结果:

CompanyName        Number of Products

Exotic Liquids     5
New Orleans Cajun  8
Grandma Kelly's    3

任何帮助将不胜感激。

【问题讨论】:

  • Microsoft SQL Server 还是 MySQL?
  • 您的意思是HAVING 而不是ORDER BY

标签: mysql sql sql-server tsql group-by


【解决方案1】:

您需要一个having 子句来过滤每个公司的产品数量。即使在查询不会失败的 MySQL 中,它也不会达到您想要的效果:它将拥有 3 种或更多产品的公司放在首位,但不会从结果集中逐出。

另外,请考虑使用 标准 联接而不是老式的隐式联接。

select s.companyName, count(*) no_products
from suppliers s
inner join products p on p.supplierID = s.supplierID
group by s.supplierID, s.companyName
having count(*) >= 3
order by s.supplierID

请注意,在 SQL Server 中,您还可以为此使用横向连接,这可能更有效:

select s.*, p.no_products
from suppliers
cross apply (select count(*) no_products from products p where p.supplierID = s.supplierID) p
where p.no_products >= 3
order by s.supplierID

【讨论】:

  • 非常感谢,我现在明白我的错误了。
  • @EttienneVanZyl:没问题!谢谢。
【解决方案2】:
SELECT   
        S.CompanyName
    ,   'Number of Products'    =   SUM(1)

FROM    @Supplier   S
JOIN    @Product    P   ON  P.SupplierID    =   S.SupplierID

GROUP BY 
        S.CompanyName

HAVING  SUM(1) > 2

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多