Run the Update Statement from another Select in SQL query - sql

I am trying to create an update query that will update my table values based on pallet number match.
SELECT [pallet] [quantity]
FROM dba.Inventory
This will returns 2 columns, one with pallet and the other with count.
I need to put this in a update statement that will match each pallet between here and table TABLE1 and update the counts in TABLE1

Use Common Table Expression.
Syntax goes like
with CTE_Values()
AS
( --- Your Statement---)
Update T
Set Col = C.col
From Table T Join CTE_Values C
On .....

I think that one easy solution (without evaluating the SELECT itself that looks quite convoluted) is to put the whole SELECT into a CTE and use it as source for your update. Something like this:
;WITH SrcCte AS (
SELECT pallet, SUM(total) as quantity
FROM (
SELECT r1.pallet, total
FROM
(SELECT plet_nbr, COUNT(serl_nbr) as total FROM Inventory group by plet_nbr )c1
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available')r1
on r1.pallet = c1.plet_nbr
UNION all
Select r2.pallet, sum(iloc_qty) as total
FROM
(SELECT plet_nbr, iloc_qty FROM Inventory WHERE([matl_nbr] Like '#%')) c2
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available') r2
on r2.pallet = c2.plet_nbr
where iloc_qty is not null
GROUP BY r2.pallet
)
AS final
GROUP BY pallet
)
UPDATE Dest
SET Dest.Cnt = Src.Quantity
FROM Table1 AS Dest
JOIN SrcCte AS Src ON Src.pallet = Dest.pallet

Related

Needing to access table from subquery in main update query

I'm in need of a way to access a column from the inner table from a subquery, which I have included below with database/table names changed. The inner query returns all of the Item_Ids of Items that have a specific term config and belong to a specific customer. Obviously, the SET currently doesn't work as I can't access any of the rows of let from the main query.
I'm fairly new to SQL and am struggling to wrap my head around how I might convert this to using joins instead of a subquery. The problem is that I need to be able to set ALL of the Grand Totals for any of the Item_Ids that come from the subquery.
UPDATE [Database].[dbo].[Items]
SET GrandTotal = GrandTotal / let.CurrentValue
WHERE Id IN (
SELECT let.Item_Id
FROM [Database].[dbo].[ItemTerms] let
WHERE TermConfig_Id = 'TERM_CONFIG_ID'
AND Item_Id IN (
SELECT le2.Id
FROM [Database].[dbo].[LaneExhibits] le2
WHERE Customer_Id = 'CUST_ID'
)
)
EDIT: Add Sample Row from Subquery
Columns are Id, DataValueStatus, CurrentValue, PreviousValue, Item_Id, TermConfig_Id. The subquery only returns the Item_Id but that is the rest of the data.
424C8BF4-0FCB-E711-80C9-005056BA0972 1 460 NULL 2D4C8BF4-0FCB-E711-80C9-005056BA0972 B8FCE730-27BE-E711-80C9-005056BA0972
The inner join version:
UPDATE i
SET GrandTotal = GrandTotal / let.CurrentValue
FROM [Database].[dbo].[Items] i
INNER JOIN [Database].[dbo].[ItemTerms] let ON i.Id=let.Item_Id
WHERE TermConfig_Id = 'TERM_CONFIG_ID'
AND Item_Id IN (
SELECT le2.Id
FROM [Database].[dbo].[LaneExhibits] le2
WHERE Customer_Id = 'CUST_ID'
)
Merge is your friend https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017
simplified sample from your example
MERGE [Database].[dbo].[Items] AS target
USING (SELECT let.Item_Id, let.CurrentValue FROM [Database].[dbo].[ItemTerms] let
/* other joins and filters here */
) AS source (Item_Id, CurrentValue)
ON (target.Item_Id = source.id /* or what you want */)
WHEN MATCHED THEN
UPDATE SET GrandTotal = source.GrandTotal / source.CurrentValue

SQL Group By Clause and Empty Entries

I have a SQL Server 2005 query that I'm trying to assemble right now but I am having some difficulties.
I have a group by clause based on 5 columns: Project, Area, Name, User, Engineer.
Engineer is coming from another table and is a one to many relationship
WITH TempCTE
AS (
SELECT htce.HardwareProjectID AS ProjectId
,area.AreaId AS Area
,hs.NAME AS 'Status'
,COUNT(*) AS Amount
,MAX(htce.DateEdited) AS DateModified
,UserEditing AS LastModifiedName
,Engineer
,ROW_NUMBER() OVER (
PARTITION BY htce.HardwareProjectID
,area.AreaId
,hs.NAME
,htce.UserEditing ORDER BY htce.HardwareProjectID
,Engineer DESC
) AS row
FROM HardwareTestCase_Execution AS htce
INNER JOIN HardwareTestCase AS htc ON htce.HardwareTestCaseID = htc.HardwareTestCaseID
INNER JOIN HardwareTestGroup AS htg ON htc.HardwareTestGroupID = htg.HardwareTestGroupId
INNER JOIN Block AS b ON b.BlockId = htg.BlockId
INNER JOIN Area ON b.AreaId = Area.AreaId
INNER JOIN HardwareStatus AS hs ON htce.HardwareStatusID = hs.HardwareStatusId
INNER JOIN j_Project_Testcase AS jptc ON htce.HardwareProjectID = jptc.HardwareProjectId AND htce.HardwareTestCaseID = jptc.TestcaseId
WHERE (htce.DateEdited > #LastDateModified)
GROUP BY htce.HardwareProjectID
,area.AreaId
,hs.NAME
,htce.UserEditing
,jptc.Engineer
)
The gist of what I want is to be able to deal with empty Engineer columns. I don't want this column to have a blank second entry (where row=2).
What I want to do:
Group the items with "row" value of 1 & 2 together.
Select the Engineer that isn't empty.
Do not deselect engineers where there is not a matching row=2.
I've tried a series of joins to try and make things work. No luck so far.
Use j_Project_Testcase PIVOT( MAX(Engineer) for Row in ( [1], [2] ) then select ISNULL( [1],[2]) to select the Engineer value
I can give you a more robust example if you set up a SQL fiddle
Try reading this: PIVOT and UNPIVOT

How to increment a column based on two tables that are joined

I am trying to increment a column on a sql server table based on the join between the initial table and the joined table. The idea is to update tblForm10Objectives, set the ObjectiveNumber column to an increment number starting with 1 based on the number of rows returned from the join of tblForm10GoalsObjectives and tblForm10Objectives where ID_Form10Goal equals a number. Example query so far:
Update tblForm10Objectives
Set ObjectiveNumber = rn
From (
Select ROW_NUMBER() over (PARTITION by OG.ID_Form10Goal) as rn
, *
From (
Select *
From tblForm10GoalsObjectives OG
Join tblForm10Objectives O On OG.ID_Form10Objective = O.ID_Form10Objective
Where OG.ID_Form10Goal = 4
Order by O.ID_Form10Objective
) as tblForm10Objectives;
If the select portion of the query is performed the columns are displayed so you can see the ObjectiveNumber is currently 0 where ID_Form10Goal = 4
Once the update runs I need for the ObjectiveNumber to show 1 , 2; since there are two rows for ID_Form10Goal = 4.
I had to introduce a new table to the logic of this update statement, the table name is tblForm10Goals. The objectives need to be pulled by ID_Agency instead of ID_Form10Goal I am getting an error message stating a "a multipart identifier 'dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective' could not be bound. I am using the following SQL Update statement:
UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM tblForm10Goals As g
Left Join tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
Right Join
(
SELECT
ROW_NUMBER() OVER (PARTITION BY g.ID_Agency
ORDER BY OB.ID_Form10Objective) AS rn,
OB.ID_Form10Objective
FROM tblForm10Goals g
LEFT JOIN dbo.tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
RIGHT JOIN dbo.tblForm10Objectives OB ON gobs.ID_Form10Objective = OB.ID_Form10Objective
Where g.ID_Agency = 2
) rns ON dbo.tblForm10Objectives.ID_Form10Object = rns.ID_Form10Objective
Your example seems to be missing a closing parenthesis somewhere, and without the table structures to look at, I can't be certain of my answer. It seems you have two tables:
tblForm10Objectives
-------------------
ID_Form10Objective
ObjectiveNumber
...
and
tblForm10GoalsObjectives
------------------------
ID_Form10Goal
ID_Form10Objective
...
If this is the case, the following query should give you the results you desire:
UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM dbo.tblForm10Objectives INNER JOIN
(
SELECT
ROW_NUMBER() OVER (PARTITION BY OG.ID_Form10Goal
ORDER BY O.ID_Form10Objective) AS rn,
O.ID_Form10Objective
FROM dbo.tblForm10Objectives O INNER JOIN
dbo.tblForm10GoalsObjectives OG ON OG.ID_Form10Objective = O.ID_Form10Objective
Where OG.ID_Form10Goal = 4
) rns ON dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective
If you run the inner SELECT statement, you will see the desired ObjectiveNumber values and the corresponding ID_Form10Objective that will get updated with those values.
If you post your table structures, I or someone else may be able to be of more help.

sql using select and adding to a table

SELECT `pro`.`St`, `s`.`Quantity`
FROM `s`
LEFT JOIN `web`.`pro` ON `s`.`Pro_id` = `pro`.`ProdID`
the above query results in a table like
st quantity
132 1
11 1
st is from one table and quantity is from another
using this select statement I want to add the resulting quantity to the st row in the other table.
Basically updating the second table by adding the quantity i get from this select statement.
UPDATE `web`.`pro`
SET `pro`.`st` = `pro`.`st` + `s`.`Quantity`
FROM `web`.`pro`
JOIN `shopping cart` `s`
ON `s`.`Pro_id` = `pro`.`ProdID`;
Something like that ?

Inserting Column From Into Another Table Trough Query

How do I update the Range field of of this table below
(don't mind the '1' values from the range above, it's supposed to be NULL)
with the Range values of this table below
When I inner join the table with the other on their EquipmentCode the values are doubled like this:
This was the query I used:
SELECT
C.*,
R.Range AS RangeFromOtherTable
FROM
EquipmentCalibrationRef AS C
INNER JOIN
Range AS R
ON
R.EquipmentCode = C.EquipmentCode
As a start, you can use following statement to get a pseudo 1 to 1 match
SELECT ecr.*, r.[Range]
FROM EquipmentCalibrationRef ecr
INNER JOIN (
SELECT RefNo = ROW_NUMBER() OVER (PARTITION BY EquipmentCode ORDER BY [Range]), *
FROM [Range] r
) r ON r.RefNo = ecr.RefNo AND r.EquipmentCode = c.EquipmentCode