SQL中一个字段的多个条件计数

时间:2010-09-28 10:32:33

标签: sql ms-access count

我有两个表,其中一个包含作者deatils和其他文章详细信息。一位作者可能有很多文章。在文章表中有一个名为“决定”的字段

决策字段可以是“已接受”或“已拒绝”。我想要一个查询来输出一个作者姓名和ID的表,然后是他们提交,接受和拒绝的数量的计数。问题出现了(我对SQL很新,所以请耐心等待)因为目前我使用的是WHERE Article.Decision =“Accept”或者某种类似的东西,并且无法找到如何在其他生成的字段中建立单独的依赖没有破坏语法。任何帮助非常感谢!

道歉,这是当前的SQL语句,它返回具有匹配和计数的作者。只是一个表达式返回此表与具有空计数的作者将是好的(然后我可以添加单独的查询来构建整个事物)

SELECT Authors.[Corresponding Author URN], Authors.[Corresponding Author Surname], Count(Articles.Decision) AS CountOfDecision
FROM Authors LEFT OUTER JOIN Articles ON Authors.[Corresponding Author URN] = Articles.[Corresponding Author URN]
WHERE (((Articles.Decision)="Rejected"))
GROUP BY Authors.[Corresponding Author URN], Authors.[Corresponding Author Surname];

URN是身份证。

3 个答案:

答案 0 :(得分:4)

您可以使用案例陈述:

select   sum(case when Decision = 'Rejected' then 1 else 0 end) as RejectedCount
,        sum(case when Decision = 'Denied' then 1 else 0 end) as DeniedCount
,        sum(case when Decision = 'Discarded' then 1 else 0 end) as DiscardedCount
,        sum(case when Decision = 'Buried' then 1 else 0 end) as BuriedCount

编辑:在访问权限中,您可以使用iif代替case,例如:

select   sum(iif(Decision="Delayed",1,0)) as DelayedCount
,        sum(iif(Decision="Ignored",1,0)) as IgnoredCount
,        sum(iif(Decision="Repulsed",1,0)) as RepulsedCount
,        sum(iif(Decision="Declined",1,0)) as DeclinedCount

答案 1 :(得分:0)

SELECT 
         Authors.[Corresponding Author URN],
         Authors.[Corresponding Author SURNAME],
         SUM(CASE WHEN decision = 'Rejected' THEN 1 ELSE 0 END) Rejected,
         SUM(CASE WHEN decision = 'Accepted' THEN 1 ELSE 0 END) Accepted
FROM 
         Authors LEFT OUTER JOIN Articles ON Authors.[Corresponding Author URN] = Articles.[Corresponding Author URN]
GROUP BY 
         Authors.[Corresponding Author URN], Authors.[Corresponding Author Surname];

答案 2 :(得分:0)

您也可以使用交叉表,但我不会为此发布SQL,因为我总是只使用QBE来创建交叉表。向导应引导您完成它。结果将是名称列的行,首先是“决策”列中的每个值的列(“已接受”列和“已拒绝”列)以及每个值的计数。