带除法的 SQL“WHERE”

Cer*_*eal 1 database sql-server where-clause

因此,我想要获得产品评级并应用它来获得顶级产品。

    CREATE PROCEDURE [dbo].[TopProducts]

AS
BEGIN
    SELECT Prod_Name, Qty, ProductImage, Price, Store_Name
    FROM Product P, Store S
    WHERE ....
Run Code Online (Sandbox Code Playgroud)

在我的产品表中,您可以找到:

(
Prod_ID int not null IDENTITY(1,1),
Store_ID int not null,
Price int not null ,
Prod_Name varchar(50) not null,
Qty int not null,
ProductDescription varchar(50),
RatingSum int not null,
RatingCount int not null,
ProductImage varchar(50),
Prod_Date date,
PRIMARY KEY (Prod_ID),
FOREIGN KEY (Store_ID) REFERENCES Store(Store_ID)
);
Run Code Online (Sandbox Code Playgroud)

所以,我想放入“WHERE”条件,例如:(RatingSum/RatingCount) >= 4 ...。

我该怎么做?

编辑:为了避免混淆!评级总和,将是一个整数,其中评论者的全部评级将相互相加,而评级计数是每次用户评论该特定产品(此 Prod_ID)时都会增加的东西,在此之后,评级就是您得到的从这个除以那个!

有没有更好的方法来获取多个评论者对特定产品的平均评分?

Gor*_*off 5

首先,你可以这样做:

WHERE (RatingSum/RatingCount) >= 4 
Run Code Online (Sandbox Code Playgroud)

在你的查询中。为了避免被零除,我建议将其更改为:

WHERE RatingSum >= 4 * RatingCount >= 4 
Run Code Online (Sandbox Code Playgroud)

或者:

WHERE (RatingSum/NULLIF(RatingCount, 0) >= 4 
Run Code Online (Sandbox Code Playgroud)

另外,切勿在from子句中使用逗号。始终使用显式join语法。

  • `HAVING` 应该仅用于 **聚合** 值 - 例如,如果您有一个 `SUM(...)` 或 `AVG(...)` 并且您需要对该聚合应用一个条件。 (2认同)