How to retrieve count of records in SELECT statement - sql

I am trying to retrieve the right count of records to mitigate an issue I am having. The below query returns 327 records from my database:
SELECT DISTINCT COUNT(at.someid) AS CountOfStudentsInTable FROM tblJobSkillAssessment AS at
INNER JOIN tblJobSkills j ON j.jobskillid = at.skillid
LEFT JOIN tblStudentPersonal sp ON sp.someid2 = at.someid
INNER JOIN tblStudentSchool ss ON ss.monsterid = at.someid
INNER JOIN tblSchools s ON s.schoolid = ss.schoolid
INNER JOIN tblSchoolDistricts sd ON sd.schoolid = s.schoolid
INNER JOIN tblDistricts d ON d.districtid = sd.districtid
INNER JOIN tblCountySchools cs ON cs.schoolid = s.schoolid
INNER JOIN tblCounties cty ON cty.countyid = cs.countyid
INNER JOIN tblRegionUserRegionGroups rurg ON rurg.districtid = d.districtid
INNER JOIN tblGroups g ON g.groupid = rurg.groupid
WHERE ss.graduationyear IN (SELECT Items FROM FN_Split(#gradyears, ',')) AND sp.optin = 'Yes' AND g.groupname = #groupname
Where I run into trouble is trying to reconcile that with the below query. One is for showing just a count of all the particular students the other is showing pertinent information for a set of students as needed but the total needs to be the same and it is not. The below query return 333 students - the reason is because the school the student goes to is in two separate counties and it counts that student twice. I can't figure out how to fix this.
SELECT DISTINCT #TableName AS TableName, d.district AS LocationName, cty.county AS County, COUNT(DISTINCT cc.monsterid) AS CountOfStudents, d.IRN AS IRN FROM tblJobSkillAssessment AS cc
INNER JOIN tblJobSkills AS c ON c.jobskillid = cc.skillid
INNER JOIN tblStudentPersonal sp ON sp.monsterid = cc.monsterid
INNER JOIN tblStudentSchool ss ON ss.monsterid = cc.monsterid
INNER JOIN tblSchools s ON s.schoolid = ss.schoolid
INNER JOIN tblSchoolDistricts sd ON sd.schoolid = s.schoolid
INNER JOIN tblDistricts d ON d.districtid = sd.districtid
INNER JOIN tblCountySchools cs ON cs.schoolid = s.schoolid
INNER JOIN tblCounties cty ON cty.countyid = cs.countyid
INNER JOIN tblRegionUserRegionGroups rurg ON rurg.districtid = d.districtid
INNER JOIN tblGroups g ON g.groupid = rurg.groupid
WHERE ss.graduationyear IN (SELECT Items FROM FN_Split(#gradyears, ',')) AND sp.optin = 'Yes' AND g.groupname = #groupname
GROUP BY cty.county, d.IRN, d.district
ORDER BY LocationName ASC

If you just want the count, then perhaps count(distinct) will solve the problem:
select count(distinct at.someid)
I don't see what at.someid refers to, so perhaps:
select count(distinct cc.monsterid)

Related

I need to group (tbl_types.name AS type) in a same row (postgres 14)

I need help with a select in postgres, I need to group X types into a single line, for example: type: multiple, trully, I need help on the type column
SELECT tbl_questions.id AS id,
tbl_questions.question AS question,
tbl_questions.year AS year,
tbl_question_responses.response_id AS response_id,
tbl_responses.response AS response_content,
tbl_responses.response_type AS response,
tbl_subjects.name AS subject,
tbl_categories.name AS category,
tbl_types.name AS type,
tbl_institutions.name AS institution
FROM tbl_questions
INNER JOIN tbl_question_responses ON tbl_questions.id = tbl_question_responses.question_id
INNER JOIN tbl_responses ON tbl_question_responses.response_id = tbl_responses.id
INNER JOIN tbl_question_subjects ON tbl_questions.id = tbl_question_subjects.question_id
INNER JOIN tbl_subjects ON tbl_subjects.id = tbl_question_subjects.subject_id
INNER JOIN tbl_question_categories ON tbl_questions.id = tbl_question_categories.question_id
INNER JOIN tbl_categories ON tbl_categories.id = tbl_question_categories.category_id
INNER JOIN tbl_question_types ON tbl_questions.id = tbl_question_types.question_id
INNER JOIN tbl_types ON tbl_types.id = tbl_question_types.type_id
INNER JOIN tbl_question_institutions ON tbl_question_institutions.question_id = tbl_questions.id
INNER JOIN tbl_institutions ON tbl_institutions.id = tbl_question_institutions.institution_id
WHERE tbl_questions.id = 'c7aa15cb-27e5-4f28-9141-483f7cce8e56'
This is a select result

How to get rid of duplicating data in every row?

SELECT distinct AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount
FROM ApplicationDetails AD
LEFT JOIN ApplicationFormsDetails AS b ON (AD.referencenumber = b.referencenumber)
LEFT JOIN ScheduleSummaries AS SS ON (AD.ReferenceNumber = SS.ReferenceNo)
INNER JOIN AppTypes as at on ss.ItemCode = at.Category
INNER JOIN Companies AS C ON (AD.CompanyId = C.CompanyID)
INNER JOIN Zones Z ON (C.ZoneCode = Z.ZoneCode)
INNER JOIN ZoneGroups ZG ON (Z.ZoneGroup = ZG.ZoneGroupId)
LEFT JOIN AssessmentUsedItems au on ah.AssessmentHeaderId = au.HeaderId
WHERE AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31' AND ZG.ZoneGroupCode = 'HO' and ah.referencenumber = 'N-101317-A1-02'
GROUP BY AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount--, ah.ApplicationForm,au.Amount
The output of this query is its duplicating the amount for every AssignTO.
Output :
Maybe you want to try using SUM(ISNULL(au.amount, 0)) AS amount instead of au.amount and remove au.amount from the GROUP BY as well...
Try this query:
SELECT AD.ReferenceNumber,
AD.ProjectTitle,
Z.ZoneCode,
C.CompanyName,
SS.AssignedTo,
ZG.ZoneGroupName,
SUM(COALESCE(au.Amount,0)) AS Amount
FROM ApplicationDetails AD
LEFT JOIN ApplicationFormsDetails AS b
ON (AD.referencenumber = b.referencenumber)
LEFT JOIN ScheduleSummaries AS SS
ON (AD.ReferenceNumber = SS.ReferenceNo)
INNER JOIN AppTypes AS at
ON ss.ItemCode = at.Category
INNER JOIN Companies AS C
ON (AD.CompanyId = C.CompanyID)
INNER JOIN Zones Z
ON (C.ZoneCode = Z.ZoneCode)
INNER JOIN ZoneGroups ZG
ON (Z.ZoneGroup = ZG.ZoneGroupId)
LEFT JOIN AssessmentUsedItems au
ON ah.AssessmentHeaderId = au.HeaderId
WHERE AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31'
AND ZG.ZoneGroupCode = 'HO'
AND ah.referencenumber = 'N-101317-A1-02'
GROUP BY
AD.ReferenceNumber,
AD.ProjectTitle,
Z.ZoneCode,
C.CompanyName,
SS.AssignedTo,
ZG.ZoneGroupName

MSSQL How do I get average of four records from different tables?

I have four tables and I need to find the average of each score for a particular id. I do not need the ENTIRE Column average, but the average of each record with the same id in each table.
I have tried this:
SELECT DISTINCT M.system_id, S.name, SUM(A.Score + WAL.score + F.score + WIN.score) / 4
AS avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name
:
Thanks for your help!
No Sum needed (and no grouping too)
SELECT DISTINCT M.system_id, S.name, (IsNull(A.Score, 0) + IsNull(WAL.score, 0) + IsNull(F.score, 0) + IsNull(WIN.score, 0)) /4
as avgscore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
SELECT DISTINCT M.system_id
,S.name
,(ISNULL(A.Score,0) + ISNULL(WAL.score,0) + ISNULL(F.score,0) + ISNULL(WIN.score,0)) /4 as 'AvgScore'
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
If you don't want NULL values to become zeros and included in the average:
SELECT DISTINCT M.system_id, S.name, X.avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
CROSS APPLY ( SELECT AVG(s) FROM (VALUES (A.Score),(WAL.score),(F.score),(WIN.score) ) scores(s) ) X(avgScore)
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name

Add a filter parameter to ssrs report

I have a query that I need to update to allow user to filter out pending applications. I have created the parameter and tried to implement using case but it is not working or giving any error messages on how to correct it. The code is:
select distinct pers.person_fname,
pers.person_mname,
pers.person_lname,
le.nationalprovidernumber NPN,
lic.licensenumber LICENSE_NUMBER,
adr.address_line1 ADDRESS1,
adr.address_line2 ADDRESS2,
adr.address_line3 ADDRESS3,
adr.city CITY,
sp.state_province_name STATE,
adr.postal_code ZIP_CODE,
eml.email,
rtp.residencetype_name RESIDENCY,
ltp.licensetype_name LICENSE_TYPE,
lic.expirationdate DATE_OF_EXPIRATION
from odilic_admin.license lic
inner join odilic_admin.licenseststimeline lst
on lic.license_id = lst.license_id
inner join odilic_admin.licenseststype lstp
on lst.licenseststype_id = lstp.licenseststype_id
inner join odilic_admin.licensedef ldef
on lic.licensedef_id = ldef.licensedef_id
inner join odilic_admin.licensetype ltp
on ldef.licensetype_id = ltp.licensetype_id
inner join odilic_admin.residencetype rtp
on ldef.residencetype_id = rtp.residencetype_id
inner join odilic_admin.licensingentity le
on lic.licensingentity_id = le.licensingentity_id
inner join odilic_admin.individual ind
on le.licensingentity_id = ind.licensingentity_id
inner join odidir_admin.person pers
on ind.person_id = pers.person_id
left outer join odidir_admin.person_address_rel par
on pers.person_id = par.person_id
left outer join odidir_admin.address adr
on par.address_id = adr.address_id
left outer join odidir_admin.address_type atp
on adr.address_type_id = atp.address_type_id
left outer join odidir_admin.state_province sp
on adr.state_province_id = sp.state_province_id
left outer join
(select pr.person_id, em.email_id, em.email
from odidir_admin.person pr,
odidir_admin.person_email_rel pe,
odidir_admin.email em
where pr.person_id = pe.person_id
and pe.email_id = em.email_id
and email_type_id = 2) eml
on pers.person_id = eml.person_id
where
ltp.licensetype_id in (:License_type)
and lstp.licenseststype_name = 'Active'
and atp.address_type_name = 'Mailing Licensing'
and (lic.expirationdate >= current_date and
trunc(lic.expirationdate) = :Expiration_Date)
and sysdate between lst.periodbegindate and lst.periodenddate
order by lic.licensenumber
In order to get applications that are pending I need to access the table odilic_admin.licenseappl and filter out all licenses with appststype = 2 (pending). To do this I added a join to the query before the last left outer join andt hen a case at bottom for when this parameter is selected.
select distinct pers.person_fname,
pers.person_mname,
pers.person_lname,
le.nationalprovidernumber NPN,
lic.licensenumber LICENSE_NUMBER,
adr.address_line1 ADDRESS1,
adr.address_line2 ADDRESS2,
adr.address_line3 ADDRESS3,
adr.city CITY,
sp.state_province_name STATE,
adr.postal_code ZIP_CODE,
eml.email,
rtp.residencetype_name RESIDENCY,
ltp.licensetype_name LICENSE_TYPE,
lic.expirationdate DATE_OF_EXPIRATION
from odilic_admin.license lic
inner join odilic_admin.licenseststimeline lst
on lic.license_id = lst.license_id
inner join odilic_admin.licenseststype lstp
on lst.licenseststype_id = lstp.licenseststype_id
inner join odilic_admin.licensedef ldef
on lic.licensedef_id = ldef.licensedef_id
inner join odilic_admin.licensetype ltp
on ldef.licensetype_id = ltp.licensetype_id
inner join odilic_admin.residencetype rtp
on ldef.residencetype_id = rtp.residencetype_id
inner join odilic_admin.licensingentity le
on lic.licensingentity_id = le.licensingentity_id
inner join odilic_admin.individual ind
on le.licensingentity_id = ind.licensingentity_id
inner join odidir_admin.person pers
on ind.person_id = pers.person_id
left outer join odidir_admin.person_address_rel par
on pers.person_id = par.person_id
left outer join odidir_admin.address adr
on par.address_id = adr.address_id
left outer join odidir_admin.address_type atp
on adr.address_type_id = atp.address_type_id
left outer join odidir_admin.state_province sp
on adr.state_province_id = sp.state_province_id
**left outer join odilic_admin.licenseappl appl
on lic.licensingentity_id = appl.licenseappl_id**
left outer join
(select pr.person_id, em.email_id, em.email
from odidir_admin.person pr,
odidir_admin.person_email_rel pe,
odidir_admin.email em
where pr.person_id = pe.person_id
and pe.email_id = em.email_id
and email_type_id = 2) eml
on pers.person_id = eml.person_id
where
ltp.licensetype_id in (:License_type)
and lstp.licenseststype_name = 'Active'
and atp.address_type_name = 'Mailing Licensing'
and (lic.expirationdate >= current_date and
trunc(lic.expirationdate) = :Expiration_Date)
and sysdate between lst.periodbegindate and lst.periodenddate
**case :pending when = yes then appl.applststype_id !=2
end**
order by lic.licensenumber
Instead of the case I have also tried using an IF with the same result. This looks like:
if :Pending = 1
then
and appl.applststype_id != 2;
end if;
Any help to get me past this is greatly appreciated and I will be sure to vote and select most correct answer to help me solve this.
Assuming that your :pending parameter is a numeric where a value of 1 indicates that pending licences are to be excluded and you only want to exclude licence applications that are pending, try adding the following condition in place of your existing case clause:
and (:pending <> 1 or appl.applststype_id !=2)

sql query sum bringing back different results

I have the following two queries below, the Total is coming back different, but I am adding the sums in each of the query the same way. Why is the total coming back different?
select [Total Children] = (SUM(demo.NumberOfPreschoolers) + SUM(demo.NumberOfToddlers) + SUM(demo.NumberOfInfants)),
County = co.Description
from ClassroomDemographics as demo
inner join Classrooms as c on demo.Classroom_Id = c.Id
inner join Sites as s on c.Site_Id = s.Id
inner join Profiles as p on s.Profile_Id = p.Id
inner join Dictionary.Counties as co on p.County_Id = co.Id
where co.Description = 'MyCounty'
Group By co.Description
select [Number Of DLL Children] = SUM(cd.NumberOfLanguageSpeakers),
[Total Children] = (SUM(demo.NumberOfPreschoolers) + SUM(demo.NumberOfToddlers) + SUM(demo.NumberOfInfants)),
County = co.Description
from ClassroomDLL as cd
inner join Classrooms as c on cd.Classroom_Id = c.Id
inner join Sites as s on c.Site_Id = s.Id
inner join Profiles as p on s.Profile_Id = p.Id
inner join Dictionary.Counties as co on p.County_Id = co.Id
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
where co.Description = 'MyCounty'
Group by co.Description
Just a quick glance over the two querties, I would presume that:
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
in the second query is excluding results that are in the first query, therefor the aggregated values will be different.
Your join to the Classrooms table is joining with an extra table in the 2nd query.
Query 1:
from ClassroomDemographics as demo
inner join Classrooms as c on demo.Classroom_Id = c.Id
Query 2:
from ClassroomDLL as cd
inner join Classrooms as c on cd.Classroom_Id = c.Id
...
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
My bet is that the ClassroomDLL table has less data in it, or has rows with a null for one of the join criteria columns, either of which could exclude rows from the results and throw your aggregate totals off.