need max(id)for multiple rows but am receiving multiple max id's - sql-server

I need to retrieve the latest loadid by location now with multiple joins.
for example ibiza's latest loadid is 692 and there are 2 records. The query below retrieves all of the loadid's for that location and not just the max. how can i achieve bringing back the latest records by location with the max(loadid) from the query below:
select
MAX(t.loadid) AS loadid,
a.process_id,
p.partitionkey,
-- t.partitionkey,
p.partdesc,
p.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed
-- a.status,
-- a.last_updated_by as processed_by,
-- a.last_update_date
FROM
data t
INNER JOIN part p
ON t.partitionkey = p.partitionkey
INNER JOIN process a
ON t.loadid = a.process_id
INNER JOIN categ c
ON t.catkey = c.catkey
INNER JOIN balance r
ON t.RULE_ID = r.RULE_ID
WHERE
p.partname = 'ibiza'
GROUP BY
t.loadid,
a.process_id,
p.partitionkey,
t.partitionkey,
p.partdesc,
p.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed;

You can use CTE :
;WITH MaxLoadId AS
(
select MAX(t.loadid) AS loadid, p.partitionkey, p.partdesc, p.partname
FROM data t
INNER JOIN part p ON t.partitionkey = p.partitionkey
WHERE p.partname = 'ibiza'
GROUP BY p.partitionkey, p.partdesc, p.partname
)
select
mli.loadid AS loadid,
a.process_id,
mli.partitionkey,
-- t.partitionkey,
mli.partdesc,
mli.partname,
c.catname,
r.rule_name,
r.file_path,
a.execution_start_time,
a.execution_end_time,
a.records_processed
-- a.status,
-- a.last_updated_by as processed_by,
-- a.last_update_date
FROM MaxLoadId mli
INNER JOIN data t ON mli.loadid = t.loadid
INNER JOIN process a ON mli.loadid = a.process_id
INNER JOIN categ c ON t.catkey = c.catkey
INNER JOIN balance r ON t.RULE_ID = r.RULE_ID

Related

Filter a table using COUNT SQL Server

I am new to SQL. I have written the code below but am getting stuck with the COUNT function. I want to only display the ClientIDs that have 2 or more ServiceIDs on the Service table. I tried doing a nested select within the join on the Service table originally and was getting error messages. Now with the code below, I am getting an error
Msg 164, Level 15, State 1, Line 13
Each GROUP BY expression must contain at least one column that is not an outer reference.
I am trying to achieve the following. THANK YOU!
client Id
Service ID
Count
1
2
3
1
3
3
1
4
3
2
5
4
2
6
4
2
7
4
2
8
4
SELECT DISTINCT
O.OrgName,
Referral.ClientID,
Client.FirstName,
Client.LastName,
P.ProviderName AS 'School',
E.ProgramID,
LI.ListLabel AS 'Reason',
Race.ListLabel AS 'Race/Ethnicity',
Gender.ListLabel AS 'Sex/Gender',
[ServiceId],
(SELECT COUNT([ServiceID])
GROUP BY Referral.ClientID
HAVING COUNT([ServiceID]) >= 2) AS 'Number of Supports'
FROM
ProviderReferral Referral
JOIN
Provider P ON ReferFromProviderID = P.EntityID
JOIN
ProviderReferralExt ON Referral.ProviderReferralID = ProviderReferralExt.ProviderReferralID
INNER JOIN
MultiSelectValue MSV ON MSV.ContextID = Referral.ProviderReferralID
AND MSV.ContextTypeID = 87
AND MSV.ListID = 1000001179
INNER JOIN
Client ON Referral.ClientID = Client.EntityID
INNER JOIN
EnrollmentMember ON client.EntityID = EnrollmentMember.ClientID
INNER JOIN
Enrollment E ON EnrollmentMember.EnrollmentID = E.EnrollmentID
AND E.X_CMNonCM = 1
INNER JOIN
ListItem LI ON LI.ListValue = MSV.ListValue
AND LI.ListID = 1000001179
INNER JOIN
ListItem Race ON Race.ListValue = client.Race
AND Race.ListID = 1000000068
INNER JOIN
ListItem Gender ON Gender.ListValue = Client.Gender
AND Gender.ListID = 1
INNER JOIN
Service ON E.EnrollmentID = Service.EnrollmentID -- the supports table
JOIN
Organization O ON o.EntityID = p.OrganizationID
WHERE
P.OrganizationID = 33847
AND E.ProgramID = 1325
AND referral.DeletedDate = '9999-12-31'
AND o.DeletedDate = '9999-12-31'
AND enrollmentmember.DeletedDate = '9999-12-31'
ORDER BY
referral.ClientID, client.FirstName
You can use window function count as follows:
Select * from
(Select ...
...
Count([ServiceID]) over (partition by referral.clientid) as cnt
From ...
...
) t where cnt > 2;
Please note order by should be last clause in your query. Use it accordingly.
Based on the request in the comment, Adding the code into your original query as follows:
select * from
(select Referral.ClientID,
Client.FirstName,
Client.LastName,
P.ProviderName as School,
E.ProgramID,
LI.ListLabel as Reason,
Race.ListLabel as "Race/Ethnicity",
Gender.ListLabel as "Sex/Gender",
[ServiceId],
Count([ServiceID]) over (partition by referral.clientid) as cnt -- this -- added open parenthesis before partition
FROM ProviderReferral Referral
JOIN Provider P on ReferFromProviderID=P.EntityID
JOIN ProviderReferralExt on Referral.ProviderReferralID=ProviderReferralExt.ProviderReferralID
INNER JOIN MultiSelectValue MSV on MSV.ContextID = Referral.ProviderReferralID AND
MSV.ContextTypeID=87 AND MSV.ListID=1000001179
INNER JOIN Client on Referral.ClientID=Client.EntityID
INNER JOIN EnrollmentMember on client.EntityID=EnrollmentMember.ClientID
INNER JOIN Enrollment E on EnrollmentMember.EnrollmentID=E.EnrollmentID and E.X_CMNonCM=1
INNER JOIN ListItem LI on LI.ListValue = MSV.ListValue and LI.ListID = 1000001179
INNER JOIN ListItem Race on Race.ListValue=client.Race and Race.ListID=1000000068
INNER JOIN ListItem Gender on Gender.ListValue=Client.Gender and Gender.ListID=1
INNER JOIN Service on E.EnrollmentID=Service.EnrollmentID -- the supports table
JOIN Organization O on o.EntityID =p.OrganizationID
Where P.OrganizationID=33847
and E.ProgramID=1325
and referral.DeletedDate = '9999-12-31' and o.DeletedDate='9999-12-31'
and enrollmentmember.DeletedDate='9999-12-31') t
where cnt > 2 -- this
order by ClientID, FirstName

Filtering date after max date SQL

I have a table with values en date/timstamps. This table is dbo.meterdata.value. The output that i want to see is as followed: The latest date/timestamp (Max) but only the ones where te latest date/timestamp is last week. My Query is:
SELECT dbo.meter.DataImportCode
,dbo.meter.NAME
,dbo.company.NAME
,dbo.meter.MeterNumber
,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum'
,dbo.MeterOperator.Description
,dbo.meter.CumulativeReadings
FROM dbo.meter
LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID
JOIN DBO.Site ON dbo.meter.SiteID = dbo.site.SiteID
JOIN DBO.Company ON dbo.site.CompanyID = dbo.company.CompanyID
JOIN DBO.MeterOperator ON dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID
--WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() )
AND dbo.meterdata.RoundedTimeStamp IS NOT NULL
GROUP BY dbo.meter.DataImportCode
,dbo.company.NAME
,dbo.meter.NAME
,dbo.meter.MeterNumber
,dbo.MeterOperator.Description
,dbo.meter.CumulativeReadings
Example of the unfilterd result:
Example
Thank you for help and support
Try the following:
select dbo.meter.DataImportCode, dbo.meter.Name, dbo.company.Name, dbo.meter.MeterNumber,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum', dbo.MeterOperator.Description, dbo.meter.CumulativeReadings
from dbo.meter
LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID
JOIN DBO.Site on dbo.meter.SiteID = dbo.site.SiteID
JOIN DBO.Company on dbo.site.CompanyID = dbo.company.CompanyID
JOIN DBO.MeterOperator on dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID
--WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() )
--AND dbo.meterdata.RoundedTimeStamp is not null
GROUP BY dbo.meter.DataImportCode, dbo.company.name, dbo.meter.Name, dbo.meter.MeterNumber, dbo.MeterOperator.Description, dbo.meter.CumulativeReadings
HAVING [laatste datum] < DateAdd(day,-7,GETDATE())
If I understood you right, what you want to do is filter out the data after it has been grouped. This is done using the HAVING clause of the SELECT statement, as the above query depicts.

Make one-to-one relation between two tables that have one-to-many relation in SQL

I have these queries :
SELECT
dbo.Lines.Unit, dbo.Lines.LineNumber, dbo.Lines.DocumentNumber,
dbo.BaseMaterials.Name AS MaterialName,
dbo.MaterialDescriptions.Name AS MaterialDescription,
dbo.MaterialDescriptions.Description,
dbo.MaterialScopes.ScopeName, dbo.MaterialScopeObjectNames.ObjectName,
dbo.MaterialDescriptions.Size1, dbo.MaterialDescriptions.Size2,
dbo.MaterialDescriptions.ItemCode, dbo.Materials.Quantity,
dbo.Materials.Discipline, dbo.Materials.Id, dbo.Lines.Id AS LineId
FROM
dbo.Materials
INNER JOIN
dbo.Lines ON dbo.Materials.LineId = dbo.Lines.Id
INNER JOIN
dbo.BaseMaterials ON dbo.Lines.BaseMaterialId = dbo.BaseMaterials.Id
INNER JOIN
dbo.MaterialDescriptions ON dbo.Materials.MaterialDescriptionId = dbo.MaterialDescriptions.Id
INNER JOIN
dbo.MaterialScopes ON dbo.MaterialDescriptions.MaterialScopeId = dbo.MaterialScopes.Id
INNER JOIN
dbo.MaterialScopeObjectNames ON dbo.MaterialDescriptions.MaterialScopeObjectId = dbo.MaterialScopeObjectNames.Id
It returns 16000 records. I have another tables with joints name that has a relation with material table on lineId every material can have multi joints so my query when I add joints table is like this :
SELECT
dbo.Lines.Unit, dbo.Lines.LineNumber, dbo.Lines.DocumentNumber,
dbo.BaseMaterials.Name AS MaterialName,
dbo.MaterialDescriptions.Name AS MaterialDescription,
dbo.MaterialDescriptions.Description, dbo.MaterialScopes.ScopeName,
dbo.MaterialScopeObjectNames.ObjectName, dbo.MaterialDescriptions.Size1,
dbo.MaterialDescriptions.Size2, dbo.MaterialDescriptions.ItemCode,
dbo.Materials.Quantity, dbo.Materials.Discipline, dbo.Materials.Id,
dbo.Lines.Id AS LineId, dbo.Joints.TestPackageId
FROM
dbo.Materials
INNER JOIN
dbo.Lines ON dbo.Materials.LineId = dbo.Lines.Id
INNER JOIN
dbo.BaseMaterials ON dbo.Lines.BaseMaterialId = dbo.BaseMaterials.Id
INNER JOIN
dbo.MaterialDescriptions ON dbo.Materials.MaterialDescriptionId = dbo.MaterialDescriptions.Id
INNER JOIN
dbo.MaterialScopes ON dbo.MaterialDescriptions.MaterialScopeId = dbo.MaterialScopes.Id
INNER JOIN
dbo.MaterialScopeObjectNames ON dbo.MaterialDescriptions.MaterialScopeObjectId = dbo.MaterialScopeObjectNames.Id
INNER JOIN
dbo.Joints ON dbo.Materials.LineId = dbo.Joints.LineId
As you can see in the last line i make a join between joints and materials to access the testpackageid column in joints table .but my result returns 220000records .How can i change the join type i mean left or right to just returns 16000 records with its testpackageId
You can't using JOIN. However, you can using CROSS APPLY:
FROM . . .
dbo.MaterialScopeObjectNames
ON dbo.MaterialDescriptions.MaterialScopeObjectId = dbo.MaterialScopeObjectNames.Id CROSS APPLY
(SELECT TOP 1 j.*
FROM dbo.Joints j
WHERE dbo.Materials.LineId = j.LineId
) J
Normally, you would include an ORDER BY when using TOP so you have some control over the row being returned.
Also note that the use of table aliases makes the query easier to write and to read.
You can get it very easily with just a subquery. Leave your query as it is, and add a subquery to get that information from Joints.
SELECT dbo.Lines.Unit, dbo.Lines.LineNumber, dbo.Lines.DocumentNumber, dbo.BaseMaterials.Name AS MaterialName, dbo.MaterialDescriptions.Name AS MaterialDescription, dbo.MaterialDescriptions.Description,
dbo.MaterialScopes.ScopeName, dbo.MaterialScopeObjectNames.ObjectName, dbo.MaterialDescriptions.Size1, dbo.MaterialDescriptions.Size2, dbo.MaterialDescriptions.ItemCode, dbo.Materials.Quantity,
dbo.Materials.Discipline, dbo.Materials.Id, dbo.Lines.Id AS LineId,
(select top 1 dbo.Joints.TestPackageId from dbo.Joints where dbo.Joints.LineId = dbo.Materials.LineId)
FROM dbo.Materials INNER JOIN
dbo.Lines ON dbo.Materials.LineId = dbo.Lines.Id INNER JOIN
dbo.BaseMaterials ON dbo.Lines.BaseMaterialId = dbo.BaseMaterials.Id INNER JOIN
dbo.MaterialDescriptions ON dbo.Materials.MaterialDescriptionId = dbo.MaterialDescriptions.Id INNER JOIN
dbo.MaterialScopes ON dbo.MaterialDescriptions.MaterialScopeId = dbo.MaterialScopes.Id INNER JOIN
dbo.MaterialScopeObjectNames ON dbo.MaterialDescriptions.MaterialScopeObjectId = dbo.MaterialScopeObjectNames.Id

SQL Server - how to sum field from multiple table

I have 3 tables like this
I want to sum SewingPrice from WorkDetail table and CombinationPrice from Details table based on WorkDate in WorkHeader table. I'm using this query and it fails (returns 1700 for CombinationPrice and 80400 for SewingPrice). I want to return 1700 for CombinationPrice and 20400 for SewingPrice.
select
SUM(det.CombinationPrice) CombinationPrice,
SUM(wd.SewingPrice) SewingPrice
from
Details det
join
WorkDetail wd on det.WorkDetailId = wd.WorkDetailId
join
WorkHeader wh on wd.WorkHeaderId = wh.WorkHeaderId
where
wh.DateStart = '2013-12-20'
SELECT * FROM WorkHeader WH
INNER JOIN (SELECT SUM(SewingPrice) SumSew, WorkHeaderID
FROM WorkDetail
GROUP BY WorkHeaderID) Sew ON
WH.WorkHeaderID = Sew.WorkHeaderID
INNER JOIN (SELECT SUM(Det.CombinationPrice) SumCombo, WD.WorkHeaderID
FROM Details Det
INNER JOIN WorkDetail WD on WD.WorkDetailID = Det.WorkDetailID
GROUP BY WorkHeaderID) Combo ON
Combo.WorkHeaderID = WH.WorkHeaderID
WHERE WH.WorkDate = '2013-12-20'
As I mentioned in my comment, you have to use group by
select
wd.workHeaderID,
SUM(det.CombinationPrice) CombinationPrice,
SUM(wd.SewingPrice) SewingPrice
from
WorkHeader wh
left join
workdetail wd on wd.WorkHeaderId = wh.WorkHeaderId
left join
(select det.workdetailid ,SUM(det.CombinationPrice)combinationprice from details det group by det.workdetailid)as det on det.WorkDetailId = wd.WorkDetailId
where
wh.workdate = '20131220'
group by wd.workheaderid

JOIN codition in SQL Server

After applying join condition on two tables I want records which is maximum among records of left table
My query
SELECT a1.*,
t.*,
( a1.trnratefrom - t.trnratefrom )AS minrate,
( a1.trnrateto - t.trnrateto ) AS maxrate
FROM (SELECT a.srno,
trndate,
b.trnsrno,
Upper(Rtrim(Ltrim(b.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(b.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(b.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(b.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(b.trnunit))) AS trnunit,
b.trnratefrom,
b.trnrateto,
a.remark,
entdate
FROM mstprodrates a
INNER JOIN trnprodrates b
ON a.srno = b.srno)a1
INNER JOIN (SELECT c.srno,
trndate,
d.trnsrno,
Upper(Rtrim(Ltrim(d.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(d.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(d.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(d.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(d.trnunit))) AS trnunit,
d.trnratefrom,
d.trnrateto,
c.remark,
entdate
FROM mstprodrates c
INNER JOIN trnprodrates d
ON c.srno = d.srno) AS t
ON a1.trnstate = t.trnstate
AND a1.trnquality = t.trnquality
AND a1.trnunit = t.trnunit
AND a1.trnlength = t.trnlength
AND a1.trnarea = t.trnarea
AND a1.remark = t.remark
WHERE t.srno = (SELECT MAX(srno)
FROM a1
WHERE srno < a1.srno)
If you mean to say,
you want Records exist in Left table but not in right then use LEFT OUTER JOIN.

Resources