多列上的 SQL SUM 和 COUNT
Posted
技术标签:
【中文标题】多列上的 SQL SUM 和 COUNT【英文标题】:SQL SUM and COUNT on Multiple Columns 【发布时间】:2017-04-10 19:59:04 【问题描述】:我在 MS Access 中有如下数据:
+------------+-----------+
| DateStart | PATIssued |
+------------+-----------+
| 12/12/2004 | Yes |
+------------+-----------+
| 13/12/2004 | No |
+------------+-----------+
| 14/12/2004 | No |
+------------+-----------+
| 12/12/2004 | No |
+------------+-----------+
| 12/12/2004 | Yes |
+------------+-----------+
| 14/12/2004 | No |
+------------+-----------+
| 13/12/2004 | Yes |
我想计算过去一周每天的记录数,并在另一列中计算 PATIssued = Yes 的记录数
所以结果看起来像:
Date DayCount PATCount
Monday 3 2
Tuesday 2 1
Wednesday 2 0
我已经做到了
SELECT Format(DateValue(DateStart),"dddd") AS DayOFWeek, PATIssuedYN,
Count(Table1.DateStart) AS DayCount,
Sum(IIf([PATIssuedYN]="Yes",1,))
FROM Table1
WHERE (((Table1.DateStart) Between DateAdd("d",-7,Now()) And Now()))
GROUP BY DateValue(DateStart), PATIssuedYN;
问题是这个返回
Date PATIssuedYN DayCount PATCount
Monday No 1
Monday Yes 2 2
Tuesday No 1
Tuesday Yes 1 1
Wednesday No 2
Wednesday Yes 0 0
星期一是 12/12,星期二是 13/12 星期三是 14/12
【问题讨论】:
从您的选择和分组中删除PATIssuedYN
使用条件,即 PATIssuedYN = Yes
@ЕвгенийКондратенко 会扭曲DayCount
值
【参考方案1】:
由于您不想返回列 PatIssuedYN
,请将其从您的选择和您的组中删除:
SELECT Format(DateValue(DateStart),"dddd") AS DayOFWeek,
Count(Table1.DateStart) AS DayCount,
Sum(IIf([PATIssuedYN]="Yes",1,))
FROM Table1
WHERE (((Table1.DateStart) Between DateAdd("d",-7,Now()) And Now()))
GROUP BY DateValue(DateStart);
【讨论】:
以上是关于多列上的 SQL SUM 和 COUNT的主要内容,如果未能解决你的问题,请参考以下文章