SQL COUNT列,其中值大于value

时间:2018-09-24 20:54:31

标签: sql tsql sql-server-2012

我有一个基本的select查询,它正在查看表中的一些示例数据。我正在尝试获取三项信息。

  • 总样本(总记录)
  • 得分大于或等于85的人数
  • 有多少分数小于85的

数据:

ScoreID RecordID    Score   ErrorMarkedToQID    ErrorActionID
1   2   30  Q00019  1
2   2   100 Q20039  3
3   3   30  Q10091  3
4   3   35  Q00019  5
6   4   5   Q10091  3

这是我尝试过的:

DECLARE @startDate DATE = '2018/09/12', @endDate DATE = '2018/09/24'

SELECT COUNT(s.ScoreID) AS totalSamples,
       COUNT(CASE WHEN s.Score >= 85 THEN 1 ELSE 0 END) AS Pass,
       COUNT(CASE WHEN s.Score < 85 THEN 1 ELSE 0 END) AS Fail
  FROM [SubmissionScores] AS s
  JOIN Submission AS sub
  ON sub.SubmissionID = s.RecordID
  WHERE sub.DateSubmittedUTC BETWEEN @startDate AND @endDate

我当前的输出是所有字段都输出5,这是记录的总数。看来我的CASE逻辑不正确。

可以像我尝试的那样通过简单的查询完成吗?

2 个答案:

答案 0 :(得分:0)

DECLARE @startDate DATE = '2018/09/12', @endDate DATE = '2018/09/24'

SELECT COUNT(s.ScoreID) AS totalSamples,
       COUNT(CASE WHEN s.Score >= 85 THEN 1 ELSE NULL END) AS Pass,
       COUNT(CASE WHEN s.Score < 85 THEN 1 ELSE NULL END) AS Fail
  FROM [SubmissionScores] AS s
  JOIN Submission AS sub
  ON sub.SubmissionID = s.RecordID
  WHERE sub.DateSubmittedUTC BETWEEN @startDate AND @endDate

答案 1 :(得分:0)

Count()函数将返回与指定条件匹配的行数,但是Case()的结果为匹配和不匹配,因此在所有情况下都返回相同(总)的行数 对于Case()0或1,您可以使用sum()来汇总案例的结果

 DECLARE @startDate DATE = '2018/09/12', @endDate DATE = '2018/09/24'

SELECT COUNT(s.ScoreID) AS totalSamples,
       SUM(CASE WHEN s.Score >= 85 THEN 1 ELSE 0 END) AS Pass,
       SUM(CASE WHEN s.Score < 85 THEN 1 ELSE 0 END) AS Fail
  FROM [SubmissionScores] AS s
  JOIN Submission AS sub
  ON sub.SubmissionID = s.RecordID
  WHERE sub.DateSubmittedUTC BETWEEN @startDate AND @endDate