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

时间:2018-12-13 07:18:28

标签: sql postgresql postgresql-9.2

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"

2 个答案:

答案 0 :(得分:0)

查找错误的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

AND

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

会给您不同的答复

答案 1 :(得分:0)

如果要获取包含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