如何在 SQL 查询中查找特定月份每个地区的平均 phone 呼叫

How to find the Average of phone calls made per District for a specific month in SQL Query

您好,我需要帮助显示 sql 查询

所以我想显示特定月份每个地区的平均通话总数,例如 2015 年 1 月、2016 年 1 月、2017 年 1 月等

下面是示例数据库

id            created_on            district_name
11       January 1, 2014, 12:00 AM    azamgarh
24       January 1, 2014, 12:00 AM    badaun
7        January 1, 2014, 12:00 AM     badgam
1        January 1, 2014, 12:00 AM     bagalkot
6        January 1, 2014, 12:00 AM     baghpat
18       January 1, 2014, 12:00 AM    bahraich
4        January 1, 2014, 12:00 AM     balaghat

id是来电,created_on是日期,district_name是地区

这是我关于这个问题的代码

 select
    t.district_name as "District",
    t.created_on::date as "Date",
    COUNT(t.id) AS "Total calls",
    AVG(COUNT(t.id)) OVER() as "Average"
from t
where
    date_part('month',  t.created_on::date) = 1 
    and date_part('year',  t.created_on::date) between 2013 and 2018
group by  
    date_part('year',  t.created_on::date)
    , date_part('month',  t.created_on::date)
    , district_name, created_on

此代码仅显示 2010-2018 年 1 月份的总平均通话次数,而不是 2013-2018 年的特定年份

有人可以帮我解决这个问题吗?提前谢谢你

您可以使用 date_part 函数来 extractgroup by 月份名称和年份。

select
    t.district_name as "District",
    t.created_on::date as "Date",
    SUM(t.id) / COUNT(t.id) as average
from t
where
    date_part('month',  t.created_on::date) = 1 
    and date_part('year',  t.created_on::date) <= 2018    
group by  
    date_part('year',  t.created_on::date)
    , date_part('month',  t.created_on::date)
    , district_name

使用直接日期比较:

SELECT t.district_name as "District",
       t.created_on::date as "Date",
       SUM(t.id) / COUNT(t.id) as average
FROM t
WHERE created_on >= '2018-01-01' AND
      created_on < '2018-02-01'
GROUP BY created_on::date, district_name;

如果可能,您不想在 where 子句中的列上使用函数。以下是三个原因:

  • 它防止使用使用该列的索引。
  • 它防止使用使用该列的分区。
  • 它阻碍了优化器,因为它限制了 table 统计信息的使用。

此外,您希望按 日期 聚合而不包含时间部分,因此 GROUP BY 也已修改。