Update does not add the correct values - sql-server

My select statement returns the ids from the tables I have joined correctly(393, starting at 92 and going up 484, its not a PK field, so some ids can be used more then once) there is a total of 550 rows I need to update, when I run the update it only adds the number 92 to the table for all 550 rows.
update movements set [location] = locaID.id FROM (
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05 09:33:00.000' OR hms.CreatedOn is null )
)locaID where product = 14
what am I missing so it updates with the correct values?

My first impression of your query is that only the rows with product = 14 in movements table will be updated with the single value coming from the subquery.
If you want to update the values based on another derived table, you need some way to link the rows together - i.e a JOIN between your table being updated and the table that holds the other data (see here )
What is the common column between movements and
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and
lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05
09:33:00.000' OR hms.CreatedOn is null )
The rough syntax shouldI think be
UPDATE movements
set [location] = locaID.id
FROM movements
JOIN (
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and
lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05
09:33:00.000' OR hms.CreatedOn is null )
) locaID
ON movements.<some column> = locaID.<some column>

Related

SQLServer 2014 unable to achieve parallelism for query

I use SQLServer 2014 (120 compatibility mode) and I want a parallel execution plan for my query, but because of a few fields, it isn't. As long as field pi.Name AS ProcessName is commented I have parallelism but when it is active it isn't. The same problem is with other commented fields. Is the reason connected with an index which covers pi.ProcessGuid but not pi.Name or something more?
ExecutionPlan_Parallel
ExecutionPlan_Single
ExecutionPlan_Original
When I commented on those few fields ExecutionPlan starts to be parallel and from 30 minutes query runs only 11 seconds.
SELECT kg.Id,
ui.UserInfoGuid AS UserGuid,
ui.FullName AS UserName,
di.DeviceInfoGuid AS DeviceGuid,
di.ComputerFullName,
pi.ProcessGuid,
--pi.Name AS ProcessName,
kg.ProcessActivationGuid,
t.Caption,
whi.WebsiteHostGuid,
--whi.HostName,
wv.WebsiteGuid,
wv.[Url],
--cc.CategoryGuid,
--cc.[Name] AS CategoryName,
ca.ControlSequenceGuid,
ca.ControlActivationGuid/*
(SELECT ce.[Name] + '/' AS [text()]
FROM [raw].ControlElement AS ce
WHERE ce.ControlSequenceGuid = ca.ControlSequenceGuid
ORDER BY ce.SequenceNumber DESC
FOR xml path ('')) AS ControlTree*/
--,ac.ApplicationContextName
,kg.BeginDate AS KeystrokeBeginDate
,kg.EndDate AS KeystrokeEndDate
,kg.TotalKeyCount
,kg.KeyCount
,kg.FunctionalKeyCount
,kg.ClickCount
,kg.WheelCount
,kg.OtherKeyCount
,kg.TotalMilliseconds
,kg.ActiveMilliseconds
FROM raw.[Session] AS s
INNER JOIN raw.Monitoring AS m
ON ( m.SessionGuid = s.SessionGuid )
INNER JOIN stats.[KeystrokeGroupRcpView] AS kg
ON ( kg.MonitoringGuid = m.MonitoringGuid )
INNER JOIN dbo.UserInfo AS ui
ON ( ui.UserInfoGuid = kg.UserGuid )
INNER JOIN dbo.DeviceInfo AS di
ON ( di.DeviceInfoGuid = kg.DeviceGuid )
INNER JOIN dbo.ProcessInfo AS pi
ON ( pi.OrganizationGuid = di.OrganizationGuid
AND pi.ProcessGuid = kg.ProcessGuid )
INNER JOIN raw.Title AS t
ON ( t.TitleGuid = kg.TitleGuid )
LEFT OUTER JOIN [raw].ControlActivation AS ca
ON ca.ProcessActivationGuid = kg.ProcessActivationGuid
AND kg.BeginDate >= ca.BeginDate
AND kg.EndDate <= ca.EndDate
LEFT OUTER JOIN controls.ControlFocus AS cf
ON cf.ControlActivationGuid = ca.ControlActivationGuid
LEFT OUTER JOIN controls.ControlSequenceContext AS csc
ON csc.ControlSequenceGuid = ca.ControlSequenceGuid
LEFT OUTER JOIN controls.ApplicationContext AS ac
ON ac.ApplicationContextGuid = csc.ApplicationContextGuid
LEFT OUTER JOIN controls.ProcessControlCategory AS pcc
ON pcc.ProcessGuid = pi.ProcessGuid
AND pcc.ControlCategoryKeyGuid =
cf.ControlCategoryKeyGuid
LEFT OUTER JOIN controls.ControlCategory AS cc
ON cc.CategoryGuid = pcc.CategoryGuid
LEFT OUTER JOIN raw.WebsiteVisit AS wv
ON ( pi.IsWebBrowser = 1
AND wv.ProcessActivationGuid =
kg.ProcessActivationGuid
AND ( wv.BeginDate < kg.BeginDate
AND wv.EndDate >= kg.EndDate ) )
LEFT OUTER JOIN dbo.WebsiteHostInfo AS whi
ON ( whi.WebsiteHostGuid = wv.WebsiteHostGuid
AND whi.OrganizationGuid = di.OrganizationGuid )
WHERE kg.BeginDate > '2020-07-01' AND kg.BeginDate < '2020-07-02' and kg.UserGuid in ('A170565A-2D30-4911-5B9C-8525E2A2772B','4BE982BD-ADFC-6201-31C2-60A0BEF0D7F6','AE296576-87C6-EC2F-5A6F-E24ACE14456E')

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

Original column name from T-SQL query that yields columns AFTER the original column name was reclassified

I have a relatively standard sql query with several table joins and where clauses that all relate a loan after it has been reclassified to ORE (Other Real Estate Owned). I am trying to list the value of one of the ORIGINAL fields (category) that has been changed now that it is ORE.
Say the original category was 1 for 'Consumer' but once the loan goes to ORE, the category is a 12 which includes ALL original categories (1,2,3,4)
Therein lies the problem - I need to show the ORE loans for only say categories 1 & 2. Nothing I've tried works - I'm assuming because the where clause at the bottom of the query specifies that I need various fields that all tie to the ORE status but NOT to the original categories. I've tried subqueries (don;t work because they are 'above' the main query's where clause...
Any general guidance would be greatly appreciated. Here's the query and the subquery below it:
SELECT
A.ACCTNO
E.SNAME,
B.OREO_ID,
A.OREODATE,
GC.CATEGORY
FROM
DBO.LOAN_SYSTEM AS A
LEFT OUTER JOIN DBO.ORE AS B
ON A.OREO_ID = B.OREO_ID
LEFT OUTER JOIN DBO.LOAN_TITLE AS C
ON A.OREO_ID = C.OREO_ID AND C.SEQ = 1
LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL) AS D
ON A.OREO_ID = D.OREO_ID
LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC
ON E.[GROUP] = GC.GROUP_CODE
WHERE
D.FC_ID IS NOT NULL AND C.FORECLOSUREDATE IS NOT NULL AND GC.CATEGORY IN (1,2) --DOESN'T WORK BECAUSE ONCE IN OREO = 12
AND
E.STATUS NOT IN (2,8)
--SUBQUERY GETS ORIGINAL CATEGORY
SELECT
B.ACCTNO, C.CATEGORY
FROM DBO.LOAN_SYSTEM A
LEFT OUTER JOIN DBO.LOAN_DAILY_INFO B
ON B.ACCTNO = A.ACCTNO
AND B.TYPE = A.TYPE
LEFT OUTER JOIN DBO.TBL_GROUP_CODES C
ON C.GROUP_CODE = B.[GROUP]
LEFT OUTER JOIN DBO.TBL_LOAN_TYPES D
ON D.TYPE = A.TYPE
WHERE B.STATUS NOT IN (2,8)
AND C.CATEGORY IN (1,2)
I'm not 100% sure what you're trying to do here.. but you might need to use EXISTS here.
SELECT A.ACCTNO,
E.SNAME,
B.OREO_ID,
A.OREODATE,
GC.CATEGORY
FROM DBO.LOAN_SYSTEM AS A
LEFT OUTER JOIN DBO.ORE AS B ON A.OREO_ID = B.OREO_ID
LEFT OUTER JOIN DBO.LOAN_TITLE AS C ON A.OREO_ID = C.OREO_ID
AND C.SEQ = 1
LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL
) AS D ON A.OREO_ID = D.OREO_ID
LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC ON D.[GROUP] = GC.GROUP_CODE
WHERE D.FC_ID IS NOT NULL
AND C.FORECLOSUREDATE IS NOT NULL
AND EXISTS (
SELECT 1
FROM DBO.LOAN_DAILY_INFO F
JOIN DBO.TBL_GROUP_CODES G ON G.GROUP_CODE = F.[GROUP]
WHERE F.STATUS NOT IN (2,8)
AND G.CATEGORY IN (1,2)
AND F.ACCTNO = A.ACCTNO
AND F.TYPE = A.TYPE
)
AND D.STATUS NOT IN (2,8)

sql query assistance

I have a sql that is as under:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on p.item_code = ib.item_code
WHERE ib.on_hand <> 0
This SQL returns only those branch_no that have on_hand <> 0.
I am trying to get all the branch_nos irrespective of the on_hand field, but while still using the where on_hand clause.
Taking the on_hand clause away solves my problem, but gives me large amount of un-needed rows with 0's.
I am using SQL SERVER 2008 R2.
Thanks in advance for any guidance. Please apologize if I am missing any information.
------------------------------------------ENTIRE SQL QUERY (Updated)---------------------------------------------
select
ib.branch_no,
p.weighted_av,
p.item_code,
p.x_value,
p.y_value,
ib.on_hand,
p.on_hand as PhysicalOH,
ip.price,
i.item_code as StyleCode,
i.description,
i.cat1,
i.cat2,
i.cat3,
i.cat4,
np.is_style_yn,
si.supplier_code ,
ysv.sort as YSort
from physical as p
left outer JOIN
item_branch as ib on p.item_code = ib.item_code -- and ib.on_hand <> 0
INNER JOIN
item_price as ip on p.item_code = ip.item_code and ip.price_type = 'P1'
INNER JOIN
style_values as sv on p.style_code = sv.style_code and p.x_value = sv.value
INNER JOIN
style_values as ysv on p.style_code = ysv.style_code and p.y_value = ysv.value and ysv.axis = 'Y'
INNER JOIN
ITEM as i on p.style_code = i.item_code
INNER JOIN
NON_PHYSICAL as np ON i.item_code = np.item_code and np.is_style_yn = 1
INNER JOIN
supplier_item as si ON i.item_code = si.item_code and si.pref_supp_no = 1
where --ib.on_hand <> 0 and
sv.axis = 'X' and
i.item_code in
(SELECT ITEM.item_code
FROM ITEM
INNER JOIN
NON_PHYSICAL ON ITEM.item_code = NON_PHYSICAL.item_code
LEFT JOIN
supplier_item ON Item.item_code = supplier_item.item_code and pref_supp_no = 1
WHERE NON_PHYSICAL.is_style_yn = 1 and ITEM.cat1 = 'Verge Sportswear Ltd' )
order by
si.supplier_code,
i.cat4,
i.cat3,
i.cat2,
i.cat1,
sv.sort
Try this:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on (p.item_code = ib.item_code AND ib.on_hand <> 0)

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