简体   繁体   English

COUNT,IIF用于计数也具有匹配的特定字段值的记录的用途

[英]COUNT, IIF usage for counting records that also have a specific field value matched

Using MS Access and I have two tables, one is categories and the other is content. 使用MS Access,我有两个表,一个是类别,另一个是内容。

My initial SQL statement, included below,takes a count of each content associated to a category and returns the count associated with each category. 我的初始SQL语句(包含在下面)对与类别关联的每个内容进行计数,并返回与每个类别关联的计数。

So for each CATEGORY, I'm simply trying to return another count in which I count CONTENT that have a specific user level and are not deleted for each CATEGORY. 因此,对于每个CATEGORY,我只是试图返回另一个计数,在该计数中,我对具有特定用户级别且未针对每个CATEGORY删除的CONTENT进行计数。

Below is what I am struggling with as I am not certain you can actually use COUNT like this. 以下是我正在努力解决的问题,因为我不确定您是否可以像这样实际使用COUNT。

 COUNT(IIf([CONTENT.isDeleted]=0,1,0)) - COUNT(IIf([CONTENT.userLevel]=2)) AS userLevelCount

This is the full select statement with my addition but not working. 这是带有我的补充的完整选择语句,但不起作用。

 SELECT

 CATEGORY.categoryId,
 CATEGORY.categoryTitle,
 CATEGORY.categoryDate,
 CATEGORY.userLevel,
 Last(CONTENT.contentDate) AS contentDate,
 CATEGORY.isDeleted AS categoryDeleted,
 COUNT(IIf([CONTENT.isDeleted]=0,1,0)) AS countTotal,
 COUNT(IIf([CONTENT.isDeleted]=1,[CONTENT.contentID],Null))           AS countDeleted,
 COUNT([CONTENT.categoryId]) -      COUNT(IIf([CONTENT.isDeleted]=1,[CONTENT.contentID],Null))AS countDifference,


 COUNT(IIf([CONTENT.isDeleted]=0,1,0)) - COUNT(IIf([CONTENT.userLevel]=2)) AS userLevelCount

 FROM CATEGORY

 LEFT JOIN CONTENT ON
 CATEGORY.categoryId = CONTENT.categoryId

 GROUP BY
 CATEGORY.categoryId,
 CATEGORY.categoryTitle,
 CATEGORY.categoryDate,
 CATEGORY.userLevel,
 CATEGORY.isDeleted
 HAVING (((CATEGORY.isDeleted)=0))

 ORDER BY

 CATEGORY.categoryTitle

you should be able to use the following 您应该可以使用以下内容

SUM(IIf([CONTENT.isDeleted]=0,1,0)) - COUNT(IIf([CONTENT.userLevel]=2,1,NULL)) AS userLevelCount

COUNT will not count NULL, but it will count zero. COUNT不会计数为NULL,但会计数为零。 SUM will calculate the sum of all 1's - that's a second way of achieving the same. SUM将计算所有1的总和-这是实现相同总和的第二种方法。

IIF exists in the newer SQL versions IIF存在于较新的SQL版本中

I believe I found the solution 我相信我找到了解决方案

 Count(IIf([CONTENT.userLevel]=2,[CONTENT.contentID],Null)) AS countDifference2

This will return the count difference for CONTENT for each CATEGORY that isn't deleted and has a specific user level. 这将返回未删除且具有特定用户级别的每个CATEGORY的CONTENT的计数差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM