SQL Server : copy from one table to another where accountID matches - sql-server

I have 2 tables: tblAccounts and tblOrders. How do I copy the data in column VENUE in tblOrders to the new column I've just set up in tblAccounts also called VENUE but where the account ID matches.
I was going to try something like this:
INSERT INTO tblaccounts (venue)
SELECT venue
FROM tblorders
WHERE tblorders.accountID = tblaccounts.accountID
If that makes sense?
The tables are different sizes so I can't just copy it all across.

Since you want to copy the value of column: venue from tblOrders to tblAccounts, you should update tblAccounts instead of inserting as following.
UPDATE tblAccounts
SET
[venue] =y.[venue]
FROM tblAccounts INNER JOIN tblOrders y
ON
tblAccounts.[accountID] = y.[accountID]

Related

Replacing data in one table with data in another table using a unique ID

I'm using Access 2016 to view data from a table on our SQL server. I have a massive audit log where the record being viewed is represented by a "FolderID" field. I have another table that has values for the FolderID (represented as "fid") along with columns identifying the record's name and other ID numbers.
I want to be able to replace the FolderID value in the first table with CUSTOMER_NAME value from the second table so I know what's being viewed at a glance.
I've tried googling different join techniques to build a query that will accomplish this, but my google-fu is weak or I'm just not caffeinated enough today.
Table 1.
EventTime EventType FolderID
4/4/2019 1:23:39 PM A 12345
Table 2
fid acc Other_ID Third_ID CUSTOMER_NAME
12345 0 9875 12345678 Doe, John
Basically I want to query Table 2 to search for fid using the value in Table 1 for FolderID, and I want it to respond with the CUSTOMER_NAME associated with the FolderID/fid. The result would look like:
EventTime EventType FolderID
4/4/2019 1:23:39 PM A Doe, John
I'm stupid because I thought I was too smart to use the freaking Query Wizard. When I did, and it prompted me to create relationships and actually think about what I was doing, it came up with this.
SELECT [table1].EventTime, [table1].EventType, [table1].FolderID, [table1].ObjRef, [table1].AreaID, [table1].FileID, [table2].CUSTOMER_NAME, [table2].fid FROM [table2]
LEFT JOIN [table1] ON [table2].[fid] = [table1].[FolderID];
You can run this query and check if it helps!.
Select EventTime, EventType , CUSTOMER_NAME AS FolderID FROM Table1, Table2 Where Table1.FolderID = Table2.fid;
Basically, 'AS' is doing what you want here as you can rename your column to whatever you want.

SQL Server - Replacing NULL values with mode of column grouped by another column

I have a table (call it oldtable) and the relevant columns are name, group, zip code. I have selected those into a new table (call that newtable). My issue is that some of the zip codes in the first table are NULL. I want to replace the NULL zip codes with the mode (most common value) of their group.
For example, say a row in newtable looks like this:
Name Group ZipCode
Blah G1 NULL
I want to replace that NULL with the most common zip code over all the people in G1 in oldtable. I am having trouble even getting started on pulling the mode of one column when grouped by another column.
I am using Microsoft SQL Server 2016.
This can be done using CROSS APPLY on an UPDATE.
UPDATE n SET
zipcode = x.zipcode
FROM newtable n
CROSS APPLY( SELECT TOP 1 zipcode, COUNT(*) cnt
FROM newtable o
WHERE n.[group] = o.[group]
GROUP BY zipcode
ORDER BY cnt DESC) x
WHERE n.zipcode IS NULL;

How to do Multiple Joins with Merge Into?

I have these 3 tables
Company
id
Branch
id
Items
id
StockNumber
Company can have many branches and a branch can have many items.
Now I got to write a query that will either insert or update an item depending on conditions.
Some items can only appear once in the company and some items can appear in each branch.
The problem for me is the ones that can only appear once in the company. I think I am going to need to basically join all these tables together and do a check but I don't know how to do this join in a "Merge Into Sp"
I made a table type that looks like this
CREATE TYPE ItemTableType AS TABLE
(
BranchId INT,
CompanyId INT
Description nvarchar(Max),
StockNumber: INT
);
In my code I can pass the companyId into my tabletype
CREATE PROCEDURE dbo.Usp_upsert #Source ItemTableType readonly
AS
MERGE INTO items AS Target
using #Source AS Source
ON
// need to somehow look at the companyId so I can then find the right record reguardlesss of which branch it sits in.
Targert.CompanyId = source.CompanyId // can't do this just like this as Item doesn not have reference to company table.
Target.StockNumber = source.StockNumber
WHEN matched THEN
// update
WHEN NOT matched BY target THEN
// insert
Edit
Sample Data
Company
Id Name
1 'A'
2 'B'
Branch
Id name CompanyId
1 'A.1' 1
2 'A.2' 1
3 'B.1' 2
4 'B.2' 3
Item
Id Name StockNumber BranchId
1 Wrench 12345 1
2 Wrench 12345 3
3 Hammer 484814 2
4 Hammer 85285825 4
Now a bulk data is going to be sent into this SP via C# code and looks something like this
DataTable myTable = ...;
// Define the INSERT-SELECT statement.
string sqlInsert = "dbo.usp_InsertTvp"
// Configure the command and parameter.
SqlCommand mergeCommand = new SqlCommand(sqlInsert, connection);
mergeCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = mergeCommand.Parameters.AddWithValue("#Source", myTable);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.SourceTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
Now say when an import of records come in and the data looks like this
Wrench (Name), 12345 (StockNumber), 2 (BranchId..they are switching the branch of this item to another branch)
If I would just send this in then if I used BranchId + Stocknumber nothing would be updated and a new record would be inserted what would be wrong as now 2 branches have the same item(based on stockNumber)
If I would just use StockNumber then these 2 records would be updated.
1 Wrench 12345 1
2 Wrench 12345 3
Which is wrong as these records are from 2 different companies. Thus I need to also use the companyId, thus I need to also check the companyId.
EDIT (from comments):
I think I have to do Target Dot something. This is what I came up with so far:
MERGE INTO Items AS Target
using #Source AS Source
ON Source.CompanyID=(
SELECT TOP 1 Companies.Id
FROM Branches
INNER JOIN Companies
ON Branches.CompanyId = Companies.Id
INNER JOIN InventoryItems
ON Branches.Id = Target.BranchId
where Companies.Id = Source.CompanyId
and StockNumber = Source.StockNumber
)
The description of what you need to do is too vague for me to be specific, but you can simply do a query with JOINs as your source. I like to put it in a CTE to make it pretty like so:
WITH cte AS (SELECT query with JOINS)
MERGE INTO items AS Target
using cte AS Source
ON
EDIT: To also do a JOIN on the Target (items) you need to do it in the ON conditions:
WITH cte AS (SELECT query with JOINS)
MERGE INTO items AS Target
using cte AS Source
ON Source.CompanyID=(
SELECT TOP 1 CompanyId
FROM TableWithCompanyId
JOIN Target
ON JoinCondition=true
)...
I know yours involves two tables to get from items to company, but the example above shows you the technique that I believe you are missing.
EDIT 2, based on latest attempt:
Try it this way:
MERGE INTO Items AS Target
using #Source AS Source
ON Source.CompanyID=(
SELECT TOP 1 Companies.Id
FROM Branches
INNER JOIN Companies
ON Branches.CompanyId = Companies.Id
WHERE Branches.Id = Target.BranchId
)
and Target.StockNumber = Source.StockNumber

Select from two different tables and store calculated value in a newly created table (Microsoft SQL Server 2014)

What would be the best way to take values from two different tables like 1st table has the value of Price, where 2nd table has the value of Quantity, and I will multiply Price by Quantity and the calculated values, Total_Price which will be store in table 3 (newly created). At 1st I've tried using FUNCTION, but many error pops out, so I change it to CTE. But my teacher suggest me to not use temporary tables, because when new row data is added to the tables, we need to run the CTE again to update it everytime new record is added. Is there any other method? Thank you.
You can try something like (syntax not verified!):
INSERT INTO Table_3 (Cur_Date,Prod,Qty,Total_Price)
VALUES (GETDATE() ,
<the passed product_ID> ,
<the passed quantity> ,
(SELECT (A.Quantity * B.Price)
FROM Table_1 A ,
Table_2 B
WHERE A.Product = <Your passed product ID>
AND A.Product = B.Product
)
);
The actual phrasing will depend on your DBMS.

spx for moving values to new table

I am trying to create one spx which based upon my ID which is 1009 will move 9 columns data to new table:
The old table has 9 columns:
CD_Train
CD_Date
CD_Score
Notes_Train
Notes_Date
Notes_Score
Ann_Train
Ann_Date
Ann_Score
userid - common in both tables
ID - 1009 - only exists in this table
and my new table has:
TrainingID,
TrainingType,
Score,
Date,
Status,
userid
TrainingType will have 3 values: Notes, CD, Ann
and other fields like score will get data from notes_score and so on
and date will get data from notes_date,cd_date depending upon in which column cd training went
status will get value from Notes_Train, cd_train and so on
based upon this, I am lost how should I do it
I tried querying one sql of users table and tried to do the join but I am losing the ground how to fix it
No idea yet, how to fill your column trainingId but the rest can be done by applying some UNION ALL clauses:
INSERT INTO tbl2 (trainingType,Date,Score,Status,userid)
Select 'CD' , CD_date, CD_score, CD_Train, userid FROM tbl1 where CD_date>0
UNION ALL
SELECT 'Notes', Notes_Date, Notes_Score, Notes_Train, userid FROM tbl1 where Notes_date>0
UNION ALL
SELECT 'Ann', Ann_Date, Ann_Score, ANN_Train, userid
FROM tbl1 where Ann_date>0
I don't know as yet whether all columns are filled in each row. That is the reason for the where clauses which should filter out only those rows with relevant data in the three selected columns.

Resources