Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of columns that are already sum in sql

SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END)  WO,
    sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END)  WP, 
sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END)  HL, 
sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END)  A,**sum(WO+WP+HL+A)** 
from TRN_ATTN072013 WHERE CONVERT(varchar,Tdate,112)>'20130712' and CONVERT(varchar,Tdate,112)<'20130717' 
group by emp_no
ORDER BY emp_no

i want to sum up this columns WO,WP,HL,A how do i sum these columns

like image 820
user2583182 Avatar asked Feb 15 '23 21:02

user2583182


2 Answers

If this is SQL server then you can use CTE

with tablesum as
(
  SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END)  WO,
                          sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END)  WP,
                          sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END)  HL,
                          sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END)  A
  from TRN_ATTN072013 
  WHERE CONVERT(varchar,Tdate,112) > '20130712' and CONVERT(varchar,Tdate,112) < '20130717'
  group by emp_no      
)

select t.*, t.WO + t.WP + t.HL + t.A
from tablesum t
order by t.emp_no
like image 161
gzaxx Avatar answered Feb 18 '23 12:02

gzaxx


in mysql ;)

SELECT emp_no, wo+wp+hl+A FROM 
(SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END)  WO,
sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END)  WP, 
sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END)  HL, 
sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END)  A,**sum(WO+WP+HL+A)** 
from TRN_ATTN072013 WHERE CONVERT(varchar,Tdate,112)>'20130712' and   CONVERT(varchar,Tdate,112)<'20130717' 
group by emp_no
ORDER BY emp_no) AS SUB_Q;
like image 22
jaczes Avatar answered Feb 18 '23 12:02

jaczes