【问题标题】:SQL Server Query COUNT NULL/Blank Values and GROUP BYSQL Server 查询 COUNT NULL/Blank 值和 GROUP BY
【发布时间】:2016-11-15 01:45:00
【问题描述】:

我一直试图解决这个问题,但没有成功。我有一个名为Appraisal 的表,其中有一列StatusID。我需要计算按StatusId 分组的评估数量。 Appraisal 中的某些记录在 StatusID 中有 NULL/空白值。如果评估员使用StatusId = NULL 进行评估,最终结果将返回 0。

评估

[AppraisalId] [AppraiserId] [StatusId]
1           11111           1
2           11111           2
3           11111           NULL
4           22222           4
5           22222           NULL
...

评估状态

[AppraisalStatusId] [AppraisalStatusName]
2                   Assigned
3                   Accepted
6                   Conditionally Declined
7                   Completed
10                  On Hold
11                  Order Not Accepted

鉴定人

[AppraiserId]
11111
22222

查询:

SELECT 
    AppraisalStatus.AppraisalStatusId, 
    COUNT(ISNULL(Appraisal.StatusId, 0)) AS "number_of_orders"
FROM
    AppraisalStatus
LEFT JOIN 
    Appraisal ON AppraisalStatus.AppraisalStatusId = Appraisal.StatusId
WHERE 
    AppraiserId = :AppraiserId

JSON 格式的结果

[{
  "AppraisalStatusId": 2,
  "number_of_orders": 1
}, {
  "AppraisalStatusId": 3,
  "number_of_orders": 5
}, {
  "AppraisalStatusId": 7,
  "number_of_orders": 184
}, {
  "AppraisalStatusId": 10,
  "number_of_orders": 2
}]

【问题讨论】:

  • 您是否在某处缺少 GROUP BY?
  • 不确定,我已经阅读了很多解释。我只是无法让查询返回 "AppraisalStatusId": 6, "number_of_orders": 0

标签: sql sql-server rest


【解决方案1】:

这是你想要的吗?

SELECT aps.AppraisalStatusId, COUNT(a.StatusId) as number_of_orders
FROM AppraisalStatus aps LEFT JOIN
     Appraisal a
     ON aps.AppraisalStatusId = a.StatusId AND
        a.AppraiserId = :AppraiserId
GROUP BY aps.AppraisalStatusId;

这将为给定评估员的每个状态返回一行。如果没有匹配的记录,则值为 0。

【讨论】:

  • 这与您想要的有何不同?
  • 第一个错误:消息:无法绑定多部分标识符“ap.AppraiserId”。
【解决方案2】:

您可以使用SUM 代替COUNTGROUP BY

SELECT 
    AppraisalStatus.AppraisalStatusId, 
    SUM(IIF(Appraisal.StatusId IS NULL, 0, 1)) AS "number_of_orders"
FROM
    AppraisalStatus
LEFT JOIN 
    Appraisal ON AppraisalStatus.AppraisalStatusId = Appraisal.StatusId
WHERE 
    AppraiserId = :AppraiserId
GROUP BY AppraisalStatus.AppraisalStatusId

【讨论】:

  • 感谢您的建议,非常感谢。我收到错误消息“关键字'IS'附近的语法不正确”。经过进一步调查,IIF 在数据库版本 SQL 2008 中不是有效函数。虽然不知道为什么它抱怨 IS
  • 我使用的是 SQL Server 2012,我不确定 SQL Server 2008 是否支持IIF。您也可以使用 CASE 语句代替 IIF。
猜你喜欢
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 2021-12-19
  • 2020-08-15
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多