Joining two SQL statements in postgres - sql

How would I join both of these statements together so it comes up as one? The two counts are being done separately as it is coming from two different tables.
SELECT ril.invoice_label_id, ril.invoice_label, ril.invoice_label_code,
fp.price as fee, count(*) as ct, l.link_id
FROM consultation_chl c
INNER JOIN link_service_pct_location l on l.link_id=c.link_id
INNER JOIN medication m ON c.consult_id=m.consult_id
INNER JOIN ref_invoice_label ril ON m.formulary_id = ril.formulary_id
INNER JOIN pharmacy ph ON ph.pharmacy_id = l.id AND l.location_type_id = 3
INNER JOIN formulary f ON f.formulary_id=m.formulary_id
INNER JOIN formulary_price fp ON fp.formulary_id=f.formulary_id
WHERE l.pct_id = 1425
AND l.service_id = 4
AND c.invoice_period = '2015-04-30'
AND ril.section_id=2
AND ril.invoice_label_code in ('MEDTABS','MEDCAPS','DOXYCAPS','DOXYTABS')
AND fp.valid_from <= c.consult_date
AND (fp.valid_to >= c.consult_date OR fp.valid_to IS NULL) GROUP BY ril.invoice_label_id, ril.invoice_label, ril.invoice_label_code,
fp.price, l.link_id
SELECT ril.invoice_label_id, ril.invoice_label, ril.invoice_label_code,
ricf.fee, count(*) as ct, l.link_id
FROM consultation_chl c
INNER JOIN link_service_pct_location l on l.link_id=c.link_id
INNER JOIN medication m ON c.consult_id=m.consult_id
INNER JOIN ref_invoice_label ril ON m.formulary_id = ril.formulary_id
INNER JOIN pharmacy ph ON ph.pharmacy_id = l.id AND l.location_type_id = 3
INNER JOIN formulary f ON f.formulary_id=m.formulary_id
INNER JOIN formulary_price fp ON fp.formulary_id=f.formulary_id
INNER JOIN ref_invoice_consult_fee ricf ON ricf.invoice_label_id = ril.invoice_label_id
WHERE l.pct_id = 1425
AND l.service_id = 4
AND c.invoice_period = '2015-04-30'
AND ril.section_id=2
AND ril.invoice_label_code in ('MEDSUSP15-25','MEDSUSP16-35','MEDSUSP26-35','MEDSUSP36-45','MEDSUSP45+')
AND fp.valid_from <= c.consult_date
AND (fp.valid_to >= c.consult_date OR fp.valid_to IS NULL) GROUP BY ril.invoice_label_id, ril.invoice_label, ril.invoice_label_code,
ricf.fee, l.link_id

You should take a look at the UNION operator.
SQL UNION Operator at W3schools.com

As your selected columns each have same names
you should be able to concatenate the selects with a "UNION" keyword in between.

Related

Best Join Strategy/Indexes for SQL Server

What is the best join strategy/indexes for this query:
SELECT
kwk.*, an.AuftragDatum, an.AbgabeDatum, an.BezahltDatum, an.AuftragStatus
FROM
KundenWerbenKunden kwk
INNER JOIN
Auftrag an ON an.AuftragNummer = kwk.AuftragNummer
WHERE
kwk.Deleted = 0
Table KundenWerbenKunden has 103950 rows with 103646 Deleted = 0 ones.
Table Auftrag has 3826552 rows.
In my real query I make some more joins:
INNER JOIN
Filiale fn WITH (NOLOCK) ON an.FilialeID = fn.FilialeID
INNER JOIN
Kunde kn ON an.KundeID = kn.KundeID
OUTER APPLY
(SELECT DISTINCT KSKNr
FROM KdZuordnung
WHERE KundeID = kn.KundeID) zn
LEFT JOIN
Anrede ann WITH (NOLOCK) ON kn.Anrede = ann.Anrede
INNER JOIN
AuftragArt aa WITH (NOLOCK) ON an.AuftragArtID = aa.AuftragArtID
INNER JOIN
AuftragGrund ag WITH (NOLOCK) ON an.AuftragGrundID = ag.AuftragGrundID
INNER JOIN
AuftragType at WITH (NOLOCK) ON an.AuftragTypeID = at.AuftragTypeID
For this query:
SELECT *
FROM KundenWerbenKunden kwk INNER JOIN
Auftrag an
ON an.AuftragNummer = kwk.AuftragNummer
WHERE kwk.Geloescht = 0;
And not knowing anything about the distribution of Geloescht, I would first try indexes on KundenWerbenKunden(Geloescht, AuftragNummer) and Auftrag(AuftragNummer).

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

How to retrieve count of records in SELECT statement

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)

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

Using a sum with a distinct in SQL

I have a query that returns the data i'm looking for using a distinct, but when I SUM that data I get a wrong amount for a my hierachy point '4-2-0-0-5-2'. 4-2-0-0-5-2 has multiple rows so when I sum it, it doesn't add up correctly. What would be the best way to incorporate a distinct into a SUM statement. Any help would be appreicated. Thanks.
First query :
Select distinct B.Proj_Nbr,c.proj_cc,h.proj_cc, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per, A.Amount
from acct_bal a
inner join dim_proj b on a.dim_proj_id = b.dim_proj_id
inner join essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr
inner join dim_per_mo d on d.dim_per_mo_id = a.dim_per_mo_id
Inner Join Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id
Inner Join Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id
inner join essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr
inner join dim_org g1 on c.proj_cc = g1.cost_ctr
Where F.Fin_Lee_Nbr = 500
and c.proj_hier like '4-2-0-0-5-2%'
And A.Dim_Scnro_Id = '45'
And D.Fscl_Yr = '2014'
And b.Proj_Nbr = '9005459'
and fscl_per ='1'
RESULT of 2 rows:
9005459 0358080 0358080 4-2-0-0-5-2 Global Sales.com (iSell) 179777.09
9005459 0358080 0358057 4-2-0-0-5-5 Global Sales.com (iSell) 2257.3**
When I want to sum the data I use this query below. This gives me the two rows i'm looking for, but proj_hier 4-2-0-0-5-2 has the wrong amount because it has multiple rows.
Select B.Proj_Nbr,c.proj_cc, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per, sum(A.Amount)
from acct_bal a
inner join dim_proj b on a.dim_proj_id = b.dim_proj_id
inner join essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr
inner join dim_per_mo d on d.dim_per_mo_id = a.dim_per_mo_id
Inner Join Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id
Inner Join Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id
inner join essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr
inner join dim_org g1 on c.proj_cc = g1.cost_ctr
Where F.Fin_Lee_Nbr = 500
and c.proj_hier like '4-2-0-0-5-2%'
And A.Dim_Scnro_Id = '45'
And D.Fscl_Yr = '2014'
And b.Proj_Nbr = '9005459'
and fscl_per ='1'
group by B.Proj_Nbr,c.proj_cc,f.dim_acct_id, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per
having Sum(A.Amount) <> 0
Order By H.Proj_Hier, B.Proj_Nbr, D.Fscl_Per
Please Generalize the Question and then ask, If i understood your problem Here is solution:
General Query :
select sum(a.amountColumn) from your_table
group by agrrColumnName;
If i change your query :
Select distinct B.Proj_Nbr,c.proj_cc,h.proj_cc, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per, sum(A.Amount)
from acct_bal a
inner join dim_proj b on a.dim_proj_id = b.dim_proj_id
inner join essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr
inner join dim_per_mo d on d.dim_per_mo_id = a.dim_per_mo_id
Inner Join Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id
Inner Join Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id
inner join essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr
inner join dim_org g1 on c.proj_cc = g1.cost_ctr
Where F.Fin_Lee_Nbr = 500
and c.proj_hier like '4-2-0-0-5-2%'
And A.Dim_Scnro_Id = '45'
And D.Fscl_Yr = '2014'
And b.Proj_Nbr = '9005459'
and fscl_per ='1' group by B.Proj_Nbr;