如何从此查询中获取“temp”列值的总和?

Posted

技术标签:

【中文标题】如何从此查询中获取“temp”列值的总和?【英文标题】:How to get sum of "temp" column values from this query? 【发布时间】:2018-12-13 07:18:27 【问题描述】:

enter image description here如何获取临时列的总和:

select Split_Part("EmpName",'_',1),
       "EmployeeID",
       sum("TotalDays"::decimal) as "temp" 
from "Leave_Log" 
where date("StartDate") between '2018-01-01' and '2018-12-31' 
  and "Staus"='Approved' 
  and "EmployeeID" in (Select "UserName" 
                      from  "Master_Employees" 
                      where "Status"='Y')
group by "EmpName","EmployeeID" 
order by "EmpName"

【问题讨论】:

你的意思是嵌套聚合吗? 具有预期输出的样本数据将有所帮助 @OtoShavadze 插入的图像显示了我从查询中获得的输出。高亮显示的总数与此查询一起被排除在外。 【参考方案1】:

看起来不对 GROUP BY:

select Split_Part("EmpName",'_',1) splited_name,
       "EmployeeID",
       sum("TotalDays"::decimal) as "temp" 
from "Leave_Log" 
where date("StartDate") between '2018-01-01' and '2018-12-31' 
  and "Staus"='Approved' 
  and "EmployeeID" in (Select "UserName" 
                      from  "Master_Employees" 
                      where "Status"='Y')
group by splited_name,"EmployeeID" 
order by splited_name

例如:如果你有桌子

CREATE TABLE public.users
(
  id integer NOT NULL DEFAULT nextval('users_user_id_seq'::regclass),
  email character varying(100) NOT NULL,
  salary integer,
  CONSTRAINT users_pkey PRIMARY KEY (id),
  CONSTRAINT users_email_key UNIQUE (email)
)

然后请求

SELECT Split_Part(email, '@', 2) split_email, sum(salary)
  FROM users
  GROUP BY email
  ORDER BY email

SELECT Split_Part(email, '@', 2) split_email, sum(salary)
  FROM users
  GROUP BY split_email
  ORDER BY split_email

会给你不同的回应

【讨论】:

【参考方案2】:

如果您想获得带有total sum of temp 的列,那么您应该使用Window Functions

select Split_Part("EmpName",'_',1) splited_name,
       "EmployeeID",
       sum("TotalDays"::decimal) as "temp",
       sum(sum("TotalDays"::decimal)) OVER () as total

【讨论】:

以上是关于如何从此查询中获取“temp”列值的总和?的主要内容,如果未能解决你的问题,请参考以下文章

python, pyspark : 获取 pyspark 数据框列值的总和

如何从此表中选择并添加平均值然后排序[重复]

Laravel 查询,其中列值大于相关模型列值的总和

查询父项时如何获取猫鼬子文档数组中的值的聚合总和?

Django:分组然后通过查询计算列值的总和

MsSQL如何在一次查询中从给定的日期和仓库号获取最近的未来值和值的总和