6

我有一个根据组件状态和可用性列出功能的查询

SELECT Brand.Id
  , Brand.Name
  , Brand.Impact
  , Brand.Visibility
  , Brand.Risk
  , SUM(Brand.Impact + Brand.Visibility + Brand.Risk) AS Priority

FROM Brand 
LEFT OUTER JOIN Type 
  ON Brand.Id = Type.FeatureId 
LEFT OUTER JOIN Model 
  ON Type.Id = Model.SubFeatureId 
LEFT OUTER JOIN TestingStatus 
  ON Model.StatusId = TestingStatus.Id

WHERE (Model.IsDeleted = 'False') 
  AND (Brand.IsDeleted = 'False') 
  AND (Type.IsDeleted = 'False')
  AND (@TeamId = 0 OR Model.TeamId = @TeamId)
GROUP BY Brand.YearId, Brand.Id, Brand.Name, Brand.Impact, Brand.Visibility, Brand.Risk
HAVING (Brand.YearId = @YearId)

我的结果如下:

ID  Name    Impact  Visibility  Risk    Priority
403 Chevy   1       2           3       48
404 Nissan  1       1           1       24
405 Toyota  3       2           1       42

代替

ID  Name    Impact  Visibility  Risk    Priority
403 Chevy   1       2           3       6
404 Nissan  1       1           1       3
405 Toyota  3       2           1       6

每个品牌分别有 8、8 和 7 个型号。这意味着我的查询正在为所有人计算优先级:Impact*models + Visibility*models + Risk*models

我怎样才能让我的 SQL 查询不做那个乘法?

谢谢

4

1 回答 1

2

根据您的评论,除非我不了解您的需求,否则我认为您不需要SUM(). 我想你只想要每个模型的总数。使用SUM()您将获得听起来不像您想要的所有记录的总数。这也将删除您的GROUP BYHAVING

SELECT Brand.Id
  , Brand.Name
  , Brand.Impact
  , Brand.Visibility
  , Brand.Risk
  , (Brand.Impact + Brand.Visibility + Brand.Risk) AS Priority

FROM Brand 
LEFT OUTER JOIN Type 
  ON Brand.Id = Type.FeatureId 
LEFT OUTER JOIN Model 
  ON Type.Id = Model.SubFeatureId 
LEFT OUTER JOIN TestingStatus 
  ON Model.StatusId = TestingStatus.Id

WHERE (Model.IsDeleted = 'False') 
  AND (Brand.IsDeleted = 'False') 
  AND (Type.IsDeleted = 'False')
  AND (@TeamId = 0 OR Model.TeamId = @TeamId)
  AND (Brand.YearId = @YearId)
于 2012-04-26T23:42:41.903 回答