简体   繁体   English

如何在MS Access中编写SQL查询以通过外键对同一字段和组中的不同值进行计数

[英]How to write a SQL Query in MS Access to Count different values in same field and group by a Foreign Key

I currently have this in MS Access : 我目前在MS Access具有以下MS Access

SELECT ClassID, Count(Component) AS ActiveDuty FROM tblStudents WHERE Component = "Active_Duty" GROUP BY classID;

It gives me the correct answer which looks like this: ClassID ActiveDuty 006-14 14 007-14 12 008-14 8 它给了我正确的答案,看起来像这样: ClassID ActiveDuty 006-14 14 007-14 12 008-14 8

But if I want it to look like this what do I need to do? 但是,如果我希望它看起来像这样,该怎么办?

ClassID ActiveDuty Reserve National Guard 006-14 14 5 6 007-14 12 9 8 008-14 8 7 18

I tried using subqueries like this: 我尝试使用如下子查询:

SELECT ClassID, (SELECT COUNT(Component) FROM tblStudents WHERE Component = "ActiveDuty") AS Active_Duty,(SELECT COUNT(Component) FROM tblStudents WHERE Component = "Reserve") AS ArmyReserve, (SELECT COUNT(Component) FROM tblStudents WHERE Component = "National_Guard") AS NationalGuard FROM tblStudents WHERE Component = "Active_Duty" GROUP BY ClassID;

But this is the result I get: 但这是我得到的结果:

ClassID ActiveDuty Reserve National Guard 006-14 34 37 29 007-14 34 37 29 008-14 34 37 29

You can use MS Access' wizard to help you make a Crosstab Query for this. 您可以使用“ MS Access”向导来帮助您对此进行交叉表查询。 It will generate something like this: 它将生成如下内容:

TRANSFORM Count(tblStudents.[Component]) AS CountOfComponent
SELECT tblStudents.[ClassID], Count(tblStudents.[Component]) AS [Total Of Component]
FROM tblStudents
GROUP BY tblStudents.[ClassID]
PIVOT tblStudents.[Component];

Adding Gender could be a little more complicated depending on how you want to the table to look. 根据您希望表格的外观,添加性别可能会稍微复杂一些。 If you want three dimensional data, someone else is going to have to help you. 如果您需要三维数据,那么其他人将不得不为您提供帮助。 =) But if you don't mind a 2D solution: =)但是如果您不介意2D解决方案:

TRANSFORM Count(temp.[ComponentGender]) AS CountOfComponent
SELECT temp.[ClassID], Count(temp.[ComponentGender]) AS [Total Of ComponentGender]
FROM (SELECT ClassID, Component & "_" & Gender as ComponentGender FROM tblStudents) AS temp
GROUP BY temp.[ClassID]
PIVOT temp.[ComponentGender];

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

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