Joining two aggregate queries from the same table - SQL Server - sql

I have two queries, both are aggregated from the same table. I'm not sure if I have to join these two queries together or if it can be done with one select statement. The goal is to output a table that aggregates total charges and total refunds for each student.
Query #1:
select
s.learners_id, sum(charge.total_amount) charge_amount
from
fact_student_transactions_t charge
inner join
dim_students_t s on s.students_sk_id = charge.students_sk_id
left join
object_statuses_t os on os.object_statusid = charge.transaction_status_id
where
os.status_name = 'Success'
and charge.tran_type = 'CHARGE'
and charge.curr_in = 1
group by
s.learners_id
Query #2:
select
s.learners_id, sum(refund.total_amount) refund_amount
from
fact_student_transactions_t refund
inner join
dim_students_t s on s.students_sk_id = refund.students_sk_id
left join
object_statuses_t os on os.object_statusid = refund.transaction_status_id
where
os.status_name = 'Success'
and refund.tran_type = 'Refund'
and refund.trans_description not in ('Amount Successfully Transfered to Prepaid Balance.', 'Amount Successfully Transfered.')
and refund.payment_method != 'Transfer'
and refund.curr_in = 1
group by
s.learners_id

You can use conditional aggregation. Also, because of the nature of the where clause, the left join is unnecessary -- the unmatched records are filtered out anyway.
So:
select s.learners_id,
sum(case when st.tran_type = 'CHARGE' then st.total_amount else 0 end) as charge_amount,
sum(case when st.tran_type = 'Refund' and
st.trans_description not in ('Amount Successfully Transfered to Prepaid Balance.', 'Amount Successfully Transfered.')
and
st.payment_method <> 'Transfer'
then st.total_amount else 0
end) as refund_amount
from fact_student_transactions_t st join
dim_students_t s
on s.students_sk_id = t.students_sk_id join
object_statuses_t os
on os.object_statusid = t.transaction_status_id
where os.status_name = 'Success' and
st.curr_in = 1 and
st.tran_type in ('CHARGE', 'Refund')
group by s.learners_id

Related

Group by + Select Case

I try to query this code but i got the error massage.
"ORA-00979: not a GROUP BY expression"
Can we use case SUM and Max in group by function.
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Can we use case SUM and Max in group by function.
Yes
However, your problem is that you use PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD = 'OUT-P' inside the CASE expression and neither PROCESSMASTER.COMP_FLG nor PROCESS.MED_PROC_CD are in the GROUP BY clause or inside of an aggregation function.
You either want:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD,
PROCESSMASTER.COMP_FLG, -- Add to the group by clause
PROCESS.MED_PROC_CD -- Add to the group by clause
;
or something like:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
CASE
WHEN MAX(PROCESSMASTER.COMP_FLG) = 1
AND COUNT(CASE WHEN PROCESS.MED_PROC_CD = 'OUT-P' THEN 1 END) > 0
THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Note: this is untested as you have not provided a minimal representative example of your tables or data to test against.

Convert multiple rows to columns but as one rows

How do i achieve achieve all this records under one row since every employee has one of each NHIF, NSSF and KRA number?
Below is the query i used but the all appear separate rows.
SELECT DISTINCT
hrmemployeehdr.employeeslno,
hrmemployeehdr.employeecode,
hrmemployeehdr.employeefirstname,
hrmemployeehdr.employeemiddlename,
hrmemployeehdr.employeelastname,
hrmDesignationHdr.DesignationName,
hrmemployeehdr.DateOfBirth,
hrmemployeehdr.DateOfJoin,
hlocationhdr.locationname,
hrmEmployeeIdentityDtl.IDProofReferenceNo AS [National ID],
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 1 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS NHIF,
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 2 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS NSSF,
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 3 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS KRA,
hrmemployeestatusdtl.Email AS [Employee Email],
huser.email AS [User Account Email],
hrmEmployeeGradeHdr.GradeName,
hDepartment.DepartmentName
FROM hrmemployeehdr
JOIN hrmemployeestatusdtl ON hrmemployeestatusdtl.employeeslno = hrmemployeehdr.employeeslno
JOIN hdivision ON hdivision.divisioncode = hrmemployeestatusdtl.divisioncode
JOIN hlocationhdr ON hlocationhdr.locationcode = hrmemployeestatusdtl.workinglocationcode
JOIN hDepartment ON hDepartment.DepartmentCode = hrmemployeestatusdtl.DepartmentCode
JOIN hrmDesignationHdr ON hrmDesignationHdr.DesignationCode = hrmemployeestatusdtl.DesignationCode
JOIN hrmEmployeeCategoryHdr ON hrmEmployeeCategoryHdr.CategoryCode = hrmemployeestatusdtl.CategoryCode
JOIN hrmEmployeeGradeHdr ON hrmEmployeeGradeHdr.GradeCode = hrmemployeestatusdtl.GradeCode
LEFT JOIN huser ON huser.employeeslno = hrmemployeehdr.employeeslno
JOIN hMasterValue ON hMasterValue.MasterValueID = hrmemployeestatusdtl.MasterValue_EmploymentStatusID
JOIN hrmEmployeeIdentityDtl ON hrmEmployeeIdentityDtl.EmployeeSlno = hrmemployeehdr.EmployeeSlno
INNER JOIN hMasterValue a ON a.MasterValueID = hrmEmployeeIdentityDtl.MasterValue_IDProofTypeID
INNER JOIN hrmEmployeeDeductionSettingsDtl ON hrmEmployeeDeductionSettingsDtl.EmployeeSlno = hrmemployeehdr.EmployeeSlno
LEFT JOIN hrmDeductionHdr ON hrmDeductionHdr.DeductionCode = hrmEmployeeDeductionSettingsDtl.DeductionCode
WHERE hrmemployeestatusdtl.employeeslno NOT IN (SELECT hrmemploymentstoppageandtermination.employeeslno
FROM hrmemploymentstoppageandtermination)
AND hrmEmployeeIdentityDtl.MasterValue_IDProofTypeID = 2741005
--and hrmemployeestatusdtl.email = huser.email
--and huser.isemployee = 1
-- select * from huser
ORDER BY employeefirstname ASC;
Use conditional aggregation on the detail table to condense all those rows into one for each employee. Something like:
with edet as (select employeeslno,
max(CASE DeductionCode when 1 THEN EmployeeRegID ELSE '' END) AS NHIF,
max(CASE DeductionCode when 2 THEN EmployeeRegID ELSE '' END) AS NSSF,
max(CASE DeductionCode when 3 THEN EmployeeRegID ELSE '' END) AS KRA
from dbo.hrmEmployeeDeductionSettingsDtl
group by employeeslno)
select emp.employeeslno, ...,
edet.NHIF, edet.NSSF, edet.KRA, ...
from dbo.hrmemployeehdr as emp
inner join edet on emp.employeeslno = edet.employeeslno
...
order by ...
;
Notice the formatting changes that HELP everyone read and understand the code as well as the good habits of using aliases, schema-qualified table names, statement terminator, etc. As already mentioned, the other joins might be contributing to the problem - but this addresses the 1:3 relationship between the header and detail table.

Return a Count of 0 When No Rows

OK, I've looked this up and tried a number of solutions, but can't get it to work. I'm a bit of a novice. Here's my original query - how can I get it to return 0 for an account when there are no results in the student table?
SELECT a.NAME
,count(s.student_sid)
FROM account a
JOIN inst i ON a.inst_sid = i.root_inst_sid
JOIN inst_year iy ON i.inst_sid = iy.inst_sid
JOIN student s ON iy.inst_year_sid = s.inst_year_sid
WHERE s.demo = 0
AND s.STATE = 1
AND i.STATE = 1
AND iy.year_sid = 16
AND a.account_sid IN (
20187987
,20188576
,20188755
,52317128
,20189249
)
GROUP BY a.NAME;
Use an outer join, moving the condition on that table into the join:
select a.name, count(s.student_sid)
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
count() does not count null values, which s.student_sid will be if no rows join from student.
You need to LEFT JOIN and then SUM() over the group where s.student_sid is not null:
select
a.name,
sum(case when s.student_sid is null then 0 else 1 end) as student_count
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s
on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
This is assuming that all of the fields in the student table that you are filtering on are optional. If you don't want to enforce removal of records where, say, s.state does not equal 1, then you need to move the s.state=1 predicate into the WHERE clauses.
If, for some reason, you are getting duplicate student IDs and students are being counted twice, then you can change the aggregate function to this:
count(distinct s.student_id) as student_count
...which is safe to do as count(distinct ...) ignores null values.

how to include several count functions and group byes in one line

I am trying to get the number of customers by their types and groups all in line as such:
GroupName | GroupNotes | Count(Type1) | Count(Type2) | Count(Type3)
but instead I can only get the groupid ,the typeid and the number of types in the group by using the following query
SELECT
CustomersGroups.idCustomerGroup , Customers.type , COUNT(*)
FROM
CustomersGroups
inner Join CustomersInGroup on CustomersGroups.idCustomerGroup = CustomersInGroup.idCustomerGroup
inner Join Customers on Customers.idCustomer = CustomersInGroup.idCustomer
Group by
CustomersGroups.idCustomerGroup, Customers.type
is there a way to show them in a single line , (and show the name of the group?)
This is a "pivot" query. Some databases directly support pivot syntax. In all, you can use conditional aggregation.
Perhaps more importantly, you should learn to use table aliases. These make queries easier to write and to read:
select cg.idCustomerGroup,
sum(case when c.type = 'Type1' then 1 else 0 end) as num_type1,
sum(case when c.type = 'Type2' then 1 else 0 end) as num_type2,
sum(case when c.type = 'Type3' then 1 else 0 end) as num_type3
from CustomersGroups cg inner Join
CustomersInGroup cig
on cg.idCustomerGroup = cig.idCustomerGroup inner Join
Customers c
on c.idCustomer = cig.idCustomer
Group by cg.idCustomerGroup;

SQL joins returning multiple results

select
tmp.templatedesc Template
,sec.name Section
,q.questiontext Questions,
--,sum(case when q.responserequired = '0' then 1 else null end) as 'N/A'
--,sum(case when q.responserequired = '1' then 1 else null end) as Scored
--,count (case when (qr.weightedscore is not null and tmp.templatedesc = 'QA 30 Day Call Form' and
--sec.name = 'opening' and
--rv.reviewstatusid = 1 )then 1 else null end) as scored
----,(case when qr.weightedscore <> q.weight then rv.reviewid else null end) as fail
--count (case when qr.weightedscore is null then 1 else null end) NA,
--count (case when qr.weightedscore is not null then 1 else null end) scored,
sec.sequencenumber, q.questionnumber, qr.*
from
aqm.dbo.reviewtemplate tmp (nolock)
inner join aqm.dbo.section sec on sec.templateid =tmp.templateid
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
inner join aqm.dbo.question q on q.questionid = qr.questionid
--inner join aqm.dbo.questiontype qt on qt.questiontypeid = q.questiontypeid
--left outer join aqm.dbo.questionoption qo on qo.questionid = q.questionid
inner join aqm.dbo.review rv on tmp.templateid = rv.templateid
inner join aqm.dbo.media md on md.mediaid = rv.mediaid
inner join aqm.dbo.iqmuser ut on md.userid = ut.userid
where
rv.reviewstatusid = 1 and
tmp.templatedesc = 'QA 30 Day Call Form'
and sec.name = 'opening' and
convert(varchar,dateadd(hh,-7,rv.reviewdate), 101) = '07/07/2014'
and ut.windowslogonaccount = 'name.name'
and q.questionnumber = 4
--group by
--tmp.templatedesc , sec.name, q.questiontext, sec.sequencenumber, q.questionnumber
order by
sec.sequencenumber, q.questionnumber
the questionresultid and sectionresultid are returning multiple values
how can i fix the joins so that it doesnt return multiple values?
i have it drilled down to a date and a person so that it should only return one row of results( but that obviously didnt work)
not sure what other data i can provide
update
i think it has to do with joins
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
as those are the ones returning multiple results.
just dont know how to fix it
First, neither aqm.dbo.questiontype nor aqm.dbo.questionoption are used in your return fields or your where clause so get rid of them if they aren't required.
Second, you are OUTER JOINing on the aqm.dbo.review, but the reviewstatusid and reviewdate are required in the WHERE clause - so this should probably be an INNER JOIN.
Last, best way to debug issues like this is to comment out the COUNT statements and the GROUP BY clause - and see what raw data is being returned.