【问题标题】:How to write a SQL Query in MS Access to Count different values in same field and group by a Foreign Key如何在 MS Access 中编写 SQL 查询以计算同一字段中的不同值并按外键分组
【发布时间】:2014-10-13 06:02:07
【问题描述】:

我目前在MS Access

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

它给了我正确的答案,如下所示: ClassID ActiveDuty 006-14 14 007-14 12 008-14 8

但如果我想让它看起来像这样,我需要做什么?

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

我尝试使用这样的子查询:

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;

但这是我得到的结果:

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

【问题讨论】:

  • 也许您应该编辑您的问题并显示您尝试使用的子查询。

标签: sql database ms-access


【解决方案1】:

您可以使用 MS Access 的向导来帮助您为此进行交叉表查询。它会生成这样的东西:

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];

【讨论】:

  • 像魔法一样工作!!但是如果有办法在 SQL 中做到这一点,我很想知道以供将来参考。
  • 如果我也想包含 Gender 计数怎么办?那么每个班级的男女总人数呢?
  • 这篇文章很好地理解了 MS Access 和 TSQL 的 PIVOT 之间的区别:[link]stackoverflow.com/questions/13953134/…
【解决方案2】:

添加性别可能会稍微复杂一些,具体取决于您希望表格的外观。如果你想要三维数据,其他人将不得不帮助你。 =) 但如果您不介意 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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多