Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在Postgres/Rails中按月计算员工离职率_Sql_Ruby On Rails_Activerecord_Data Science_Data Analysis - Fatal编程技术网

Sql 在Postgres/Rails中按月计算员工离职率

Sql 在Postgres/Rails中按月计算员工离职率,sql,ruby-on-rails,activerecord,data-science,data-analysis,Sql,Ruby On Rails,Activerecord,Data Science,Data Analysis,我有一个Rails/PostgreSQL web应用程序,其中包含以下格式的employees表: # == Schema Information # # Table name: employees # # id :bigint(8) not null, primary key # first_name :string # last_name :string # hired_datetime

我有一个Rails/PostgreSQL web应用程序,其中包含以下格式的employees表:

# == Schema Information
#
# Table name: employees
#
#  id                  :bigint(8)        not null, primary key
#  first_name          :string
#  last_name           :string
#  hired_datetime      :datetime
#  terminated_datetime :datetime
我想制作一个员工保留率按月图表,如下所示(但按所有12个月或过去12个月计算):


我如何生成查询(使用ActiveRecord或straight SQL)来生成此图表所需的数据?

如果您试图保留年、月组合,我建议使用date\u trunc,否则使用date\u part

从那里,您可以创建聚合函数,如
count

SELECT count(*), date_trunc('month', terminated_datetime) 
FROM employees
GROUP BY date_trunc('month', terminated_datetime);
或者,在后面的查询中,如果您正在查找2018年12月的特定员工记录(包括第一次、最后一次等):

SELECT *, date_trunc('month', terminated_datetime) 
FROM employees 
WHERE date_trunc('month', terminated_datetime) = '2018-12-01 00:00:00';
然后,您可能会再次查看12月份离职的所有员工(无论是哪一年):

SELECT *, date_trunc('month', terminated_datetime) 
FROM employees 
WHERE date_trunc('month', terminated_datetime) = '2018-12-01 00:00:00';
SELECT *, date_part('month', terminated_datetime) 
FROM employees 
WHERE date_part('month', terminated_datetime) = 12;