【问题标题】:How to get sum of "temp" column values from this query?如何从此查询中获取“temp”列值的总和?
【发布时间】: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 插入的图像显示了我从查询中获得的输出。高亮显示的总数与此查询一起被排除在外。

标签: sql postgresql postgresql-9.2


【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多