我一直试图弄清楚这一点没有成功。我有一个名为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
...
AppraisalStatus
[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
}]
答案 0 :(得分: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.
答案 1 :(得分:0)
您可以SUM
使用COUNT
代替GROUP 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