I have a query in which works fine but I am trying to get the total for company 01 an company 15 and so on, right now its group by company how can I create another column to total /SUM them by company?
with cte as
(SELECT distinct AL_AMOUNT,CM.PAYGRP,MEMO,JO.COMPANY,CM.EMPID,CV.PAY_END_DT
FROM pay_CHK CM
join CHECKS CV on CV.EMPID =CM.EMPID
JOIN JOBs JO ON JO.PAYGRP=CM.PAYGRP
AND JO.EMPID=CM.EMPID
AND JO.EFDT=(SELECT MAX(EFDT)
FROM JOBs
WHERE EMPID=JO.EMPID
AND EFDT<=CM.CHECK_DT
)
where memo in('401')
)
SELECT SUM(AL_AMOUNT) AS TOTAL_AMOUNT, CM.PAYGRP,MEMO,COMPANY,PAY_END_DT
FROM cte CM
where pay_end_dt='11/30/18'
group BY CM.PAYGRP,company, MEMO,PAY_END_DT
Thanks harish, I can't do it because I need all the columns and those columns in group by. if I had only the Company, it could have been done. I thought may be there is a way to do this asking all the Gurus here.
another way you could do it is if you had the summation done in a subquery. but since you did not provide any sample data this might or might not work
SELECT TOTAL_AMOUNT, CM.PAYGRP,MEMO,cm,COMPANY,PAY_END_DT
FROM cte CM
join (select SUM(AL_AMOUNT) AS TOTAL_AMOUNT , company
from cte where pay_end_dt='11/30/18' group BY company) s on cm.company = s.company
where pay_end_dt='11/30/18'
Thanks Yosiaz, its not working. I have to do this in the report itself. your solution gives me so many rows for each person. sorry I cant provide data. Thanks again!
Thanks harish, yes just like above pics in one row and paygrp ... looks like you have the data do you still need it? How do I attach? I don't see the link to attach?
Pasi
use tempdb
go
drop table data
go
create table data
(
total_amount decimal(10,2) NULL,
company int NULL,
paygrp varchar(100) NULL,
memo int NULL,
pay_end_dt date NULL
)
go
insert into data select 349135.17,15,'SA3',401,'2018-11-30'
insert into data select 413346.11,15,'SA4',401,'2018-11-30'
go
select * from data
go
SQL .. comma seperated paygrp
SELECT sumtot_amt,
company,
Stuff((SELECT ',' + paygrp
FROM data
WHERE company = t.company
AND memo = t.memo
AND pay_end_dt = t.pay_end_dt
FOR xml path('')), 1, 1, ''),
memo,
pay_end_dt
FROM (SELECT company,
memo,
pay_end_dt,
Sum(total_amount) AS sumtot_amt
FROM data
GROUP BY company,
memo,
pay_end_dt) t
Never mind, its fixed had to add "DISTINCT" to select..! Thanks so much!
SELECT DISTINCT sumtot_amt,
company,
Stuff((SELECT ',' + paygrp
FROM data
WHERE company = t.company
AND memo = t.memo
AND pay_end_dt = t.pay_end_dt
FOR xml path('')), 1, 1, ''),
memo,
pay_end_dt
One thing, is there any easier way to do this with out STUFF and 2 select statments, like one line code?
SELECT company,
memo,
Stuff((SELECT distinct ',' + paygrp
FROM #data
WHERE company = t.company
AND memo = t.memo
AND pay_end_dt = t.pay_end_dt
FOR xml path('')), 1, 1, '')
pay_end_dt,
Sum(total_amount) AS sumtot_amt
FROM #data t
GROUP BY company,
memo,
pay_end_dt