【问题标题】:Access SQL query with JOIN and a COUNT statement not counting anything使用 JOIN 和不计算任何内容的 COUNT 语句访问 SQL 查询
【发布时间】:2019-03-26 17:04:46
【问题描述】:

我在 MS Access 中有两个表。一个代表行星,一个代表它所环绕的恒星类型。

我想计算每种恒星类型的行星数量......所以类似于:

+----------+--------------------+
| StarType | PlanetsPerStarType |
+----------+--------------------+
| A        |                  4 |
| B        |                  1 |
| C        |                  7 |
+----------+--------------------+

所以我写了这个 SQL 查询:

SELECT StarType, COUNT(PlanetName) AS PlanetsPerStarType
FROM Planets AS p
LEFT JOIN StarClass AS s ON p.sid = s.sid
GROUP BY starType, PlanetName

但它只是列出了所有行星和所有恒星类型的1,它根本不算数。

我做错了什么?

【问题讨论】:

  • PlanetName 不应该在GROUP BY

标签: sql ms-access ms-access-2013


【解决方案1】:

通过starType 和 PlanetName 分组,计数返回每个starType 和PlanetName 组合中的记录数,除非您有多个绕着你的恒星运行的同名行星永远是一颗。

例如,给定数据:

+-----------+------------------+
| StarType  |    PlanetName    |
+-----------+------------------+
| G2V       | Mars             |
| G2V       | Earth            |
| G2V       | Venus            |
| Red Dwarf | Omicron Persei 8 |
| Red Dwarf | Vergon 6         |
+-----------+------------------+

按StarType 和 PlanetName 分组将产生完全相同的数据,因为没有重复的StarType 和PlanetName 组合可以合并到一个组中。

因此,SQL 代码:

select t.StarType, count(t.PlanetName) as Planets
from YourTable t
group by t.StarType, t.PlanetName

会产生:

+-----------+---------+
| StarType  | Planets |
+-----------+---------+
| G2V       |       1 |
| G2V       |       1 |
| G2V       |       1 |
| Red Dwarf |       1 |
| Red Dwarf |       1 |
+-----------+---------+

因为每组恰好包含一个记录。

如果我们只按StarType 分组,Count 聚合函数将返回与每个StarType 关联的记录数:

select t.StarType, count(t.PlanetName) as Planets
from YourTable t
group by t.StarType
+-----------+---------+
| StarType  | Planets |
+-----------+---------+
| G2V       |       3 |
| Red Dwarf |       2 |
+-----------+---------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2020-07-01
    • 2018-07-09
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多