使用每月事件数创建新的 table

Create new table with number of incidents per month

伙计们,怎么了,我已经开始学习 SQL 数据库的东西了,我在这里很困惑。我必须创建一个 table 每个月的事件数。 我已经知道如何创建 table 但其余的 ?

SELECT
    EXTRACT(month FROM dateofcall) AS x,
    incidentnumber,
    dateofcall
FROM
    incidents
GROUP BY
    incidentnumber,
    x
ORDER BY
    x ASC;

但它没有给我每月事件数的结果。 =(

SELECT
    EXTRACT(month FROM dateofcall) AS theMonth,
    COUNT(*) AS theNumberOfIncidents
FROM
    incidents
GROUP BY
    EXTRACT(month FROM dateofcall)
ORDER BY
    theMonth

您的原始查询没有计算任何内容。您还按 incidentNumber 分组,我认为这是您的主键,这是一个无意义的操作。

由于 SQL 语言的一个怪癖,您不能在 GROUP BY 语句中使用列别名,这就是您需要复制 EXTRACT(month FROM dateofcall) 代码的原因。

您似乎在 GROUP BY 子句中按太多项目分组,并且您没有计算事件,只是显示它们的详细信息。

试试这个:

SELECT EXTRACT(month FROM dateofcall) AS x,
       COUNT(*) AS incidents    
FROM
   incidents
GROUP BY
    EXTRACT(month FROM dateofcall)
ORDER BY
    EXTRACT(month FROM dateofcall)