SQL Compare 2 columns from 2 tables to complete another column - sql

The tables have the following columns:
Table A:
TIN,
Fee_Sched,
Effective_Date
Table B:
TIN,
Fee_Sched,
Fee_Sched_Eff
TableB.Fee_Sched & TableB.Fee_Sched_Eff are currently blank
This is what I want to do:
I want to compare the two TIN columns and when there is a match, I want the corresponding results from TableA.Fee_Sched to print in TableB.Fee_Sched and the results from TableA.Effective_Date to print in TableB.Fee_Sched_Eff
I am assuming I would use a join or union and possibly an IF statement (if tableA.TIN = tableB.TIN, then print tableA.fee_sched and TableA.Effective_Date). But, I am not sure how I designate which column the results should stored in or how to organize the code correctly.
**Example:**
Table A
TIN Fee_Sched Effective_Date
123 ABCEDF 1/1/2011
456 ZYXABC 9/9/2009
TABLE B
TIN Fee_Sched Fee_Sched_Eff
123 blank blank
**Results:**
TABLE B
TIN Fee_Sched Fee_Sched_Eff
123 ABCEDF 1/1/2011
I've tried this:
Insert INTO dbo.TableB (Fee_Sched, Fee_Sched_Eff)
SELECT Fee_Sched, Effective_Date
FROM dbo.TableA Where dbo.TableA.TIN = dbo.TableB.TIN;
But, I get this error:
Msg 4104, Level 16, State 1, Line 3 The multi-part identifier
"dbo.TableB.TIN" could not be bound.

There are four basic verbs/actions in SQL:
select retrieves data
insert adds data
delete removes data
update changes data.
Update is the one you need to use. With MS SQL you can achieve your desired result using this update query:
update b
set b.Fee_Sched = a.Fee_Sched, b.Fee_Sched_Eff = Effective_Date
from TableB b
join TableA a on a.TIN = b.TIN

Well, first things first: if you want to modify table B, you are looking for an UPDATE command. Also, notice that you can use a SELECT inside the UPDATE statement, and you can reference the "outer" table from inside the SELECT. This should do the trick:
update B set B.fee_sched = (SELECT fee_sched FROM A WHERE A.TIN=B.TIN)
Finally, remember to always post which RDBMS you are using, as there may be differences on what you can write for each of them (Microsoft SQL, Oracle, MySQL?)

Related

How to update or copy data between 2 tables SQL

I have table name Merge_table like :
Employee_Number MINISTRY_CODE BRANCH_SECRETARIAT_CODE
12 333 30
13 222 31
l want to copy the value of BRANCH_SECRETARIAT_CODE and paste it in different table called EMPLOYMENTS look like :
and ENTITY_BRANCH has null data
EMPLOYEE_NUMBER JOINING_DATE ENTITY_BRANCH
12 11/12/2006 null
13 01/11/2009 null
so, now i want to copy the value of BRANCH_SECRETARIAT_CODE from table1 to
table2 ENTITY_BRANCH for each employee according his EMPLOYEE_NUMBER
You can declare several tables in your UPDATE instruction and specify which column of which table has to be updated from the values of the other table.
In your case you have only 2 tables so the easier is to make an implict jointure using T1.Employee_Number = T2.Employee_Number :
UPDATE Table1 T1, Table2 T2
SET T2.ENTITY_BRANCH = T1.BRANCH_SECRETARIAT_CODE
WHERE T1.Employee_Number = T2.Employee_Number
I guessed this is for SQL server but this UPDATE statement will work also on MySQL and Access. Please edit your question to add the proper RDBMS tag.
Use the ANSI Standard's merge statement, which provides better join-style syntax for matching source and destination tables, supports complex source clauses, supports inserts too, etc.
merge into EMPLOYMENTS -- destination table
using Merge_table -- source table, or nested subquery, CTE, etc.
on Merge_table Employee_Number = EMPLOYMENTS.EMPLOYEE_NUMBER
-- any other criteria to determine which destination rows to affect
-- e.g.: and EMPLOYMENTS.EMPLOYEE_NUMBER is null
-- when not matched then
-- [...]
when matched then
update
set EMPLOYMENTS.ENTITY_BRANCH = Merge_table.BRANCH_SECRETARIAT_CODE;

CREATE TABLE failed ORA 00957 Duplicate column name

As I tried to create new table from existing 2 table with specific column name in oracle.
I tried below code
CREATE TABLE D_T1
AS
SELECT a.col1, a.col2, a.col3, a.col4, a.col5, b.col6, b.col7, b.col8
FROM db1.table1 a INNER JOIN db1.table2 b
ON (a.col1 = b.colNum AND a.col2 = b.colnum1)
But I get error
CREATE TABLE failed ORA 00957 Duplicate column name
Can anyone help?
Ignoring the other errors you seem to have introduced by retyping the code, you've shown that you do have a duplicate column, which is what the error is telling you:
a.VALIDFLAG, b.VALIDFLAG
You seem to be under the impression that the table (alias) prefix makes the column names in the projection unique. They do not. The table prefix tells Oracle which table to get the column value from (unless you're using the using join syntax, which you are not). If the column appears in two tables you have to prefix the column name with the table. If you want the value from both tables you have to prefix both of them.
With a simple query then referring to both table columns without column aliases is OK, but something trying to consume the result set might struggle. This is fine:
select a.dummy, b.dummy
from dual a
join dual b on b.dummy = a.dummy;
DUMMY DUMMY
------- -------
X X
But notice that both columns have the same heading. If you tried to create a table using that query:
create table x as
select a.dummy, b.dummy
from dual a
join dual b on b.dummy = a.dummy;
You'd get the error you see, ORA-00957: duplicate column name.
If you alias the duplicated columns then the problem goes away:
create table x as
select a.dummy as dummy_a, b.dummy as dummy_b
from dual a
join dual b on b.dummy = a.dummy;
So in your case you can alias those columns, if you need both:
..., a.VALIDFLAG AS validflag_a, b.VALIDFLAG AS validflag_b, ...
To be completely honest, that query is a mess. You've got several errors in your SQL statement:
CREATE TABLE AS SELECT
The table name is missing - this should be
CREATE TABLE my_new_table AS SELECT
to create a new table named my_new_table.
a.ALIDFLAG,b,VALIDFLAG,
I've got a suspicion that this should really be a.VALIDFLAG instead of a.ALIDFLAG. Also, you need to replace b,VALIDFLAG with b.VALIDFLAG.
SELECT a.BILLFREQ a.CDHRNUM,
You're missing a comma after a.BILLFREQ - this is a syntax error.
a.A‌​GNYCOY,a.AGNTCOY
There's the culprit - you're selecting the same column twice. Get rid of the second one.
EDIT Actually, the names are different, so this isn't the cause of the error (unless you've mistyped your query in the comment instead of copy& paste).
To debug this kind of errors, try to
format your SQL statement in a readable way
comment out everything but one column, run the statement and ensure it works
add one column
repeat until you find the error or you've added all columns
2ND UPDATE
With the updated query, the error is here:
a.VALIDFLAG,
b,
VALIDFLAG,
You have two columns named VALIDFLAG - use an alias for one of these, and it should work.
ORA-00957: duplicate column name
The only reason for that error in your CTAS statement is that you have similar column name in the SELECT statement. Though you might be referring to different table columns, but you did not use a column alias
Error reproduce:
Using the standard EMP and DEPT table.
SQL> CREATE TABLE D_T1 AS
2 SELECT a.deptno,
3 b.deptno
4 FROM emp A
5 INNER JOIN dept b
6 ON (a.deptno = b.deptno);
b.deptno
*
ERROR at line 3:
ORA-00957: duplicate column name
Workaround:
Use proper alias:
SQL> CREATE TABLE D_T1 AS
2 SELECT a.deptno e_deptno, --add column alias
3 b.deptno d_deptno --add column alias
4 FROM emp a
5 INNER JOIN dept b
6 ON (a.deptno = b.deptno);
Table created.
Edit as per new input from OP.
You have some syntax error in your query. Corrected those. I also checked for duplicate columns. There are none. Now run this and let me know if you still get same error.
CREATE TABLE D_T1 AS SELECT
a.B, a.C,a.C, a.C, a.C,a.J, a.O,
a.P,a.P,a.S,a.S,a.R,a.B,
a.S,a.S,b.A,b.C,b.C,b.I, b.M,
b.P,b.P,b.S,b.S,b.S,b.Z,b.Z,a.C,
a.CH‌​,a.G,b,V,b.T,a.C,a.C,a.C,
a.A,a.A‌​Ga.AG
FROM tbl1 a JOIN tbl2 b
ON (a.C= b.C AND a.C1= b.C1)

Insert records into a table based on value of a record in another table

I am trying to create a quotation system using Microsoft Access 2013.
Currently, my main issue to trying to write a query that selects all records from a table (itemquote) that have a certain quoteID matching the quoteID coming from another table (currentquote), and then inserts the results into a new table (quoteditems).
Here is a basic example of the tables:
ItemQuote
UniqueID ItemID QuoteID BuyPrice SellPrice
1 1 1 10.00 11.00
2 8 2 07.00 14.00
3 4 5 01.12 03.00
CurrentQuote
CurrentQuoteID
1
My current attempt at writing the query looks like this:
INSERT INTO tblQuotedItems
SELECT *
FROM tblQuoteAsBuiltAndLabelling
INNER JOIN tblCurrentQuote
ON tblQuoteAsBuiltAndLabelling.QuoteID = tblCurrentQuote.CurrentQuoteID;
The resulting error message is "The INSERT INTO statement contains the following unknown field name: 'CurrentQuoteID'. Make sure you have typed the name correctly, and try the operation again." (Error 3127)
What should I do to my query to make it achieve the desired result? Thanks in advance.
The problem may be because your tblQuotedItems does not have the same number of column what your Select Query Returns.
So to resolve this, You can specified individual columns in INSERT Statement, and that will solve your problem.
You can not specify column names in the insert if the columns in the select are in the same order as in the table definition. Possibly, the columns in the current quote might be the same. If so, this might work:
INSERT INTO tblQuotedItems
SELECT tblCurrentQuote.*
FROM tblQuoteAsBuiltAndLabelling INNER JOIN
tblCurrentQuote
ON tblQuoteAsBuiltAndLabelling.QuoteID = tblCurrentQuote.CurrentQuoteID;
However, I strongly recommend that you include column names explicitly when you do inserts:
INSERT INTO tblQuotedItems(col1, col2, . . .)
SELECT col1, col2, . . .
FROM tblQuoteAsBuiltAndLabelling INNER JOIN
tblCurrentQuote
ON tblQuoteAsBuiltAndLabelling.QuoteID = tblCurrentQuote.CurrentQuoteID;

update multiple fields SQL

Hi my problem is I want to update a field in 1 table using another field from several tables dependant upon where the item originates my only problem is the table which im trying to update has several of the same values in so am getting 'single row sub-query returns more than 1 row'. I dont mind all of the updated fields with the same value being the same. Heres my SQL:
update URL_SET_TAB u
Set U.ITEM_NAME = (select a.PROGRAMME_NAME
from (SELECT (nvl(nvl(b.prog_name,c.movie_name), A.URL_1)) as programme_name, a.ID, a.URL_1
FROM URL_SET_TAB a, prog_name_lookup b, movie_name_lookup c
where a.url_1 = b.url_1(+) and a.url_1 = C.MOVIE_URL(+)
) a
where u.ID = a.ID and U.URL_1 = a.URL_1
)
You need to identify a key column which when matched for URL_SET_TAB and inline view a so that the subquery returns only a single record. This is a limitaion of an UPDATE clause.
Thanks,
Aditya

Writing a single UPDATE statement that prevents duplicates

I've been trying for a few hours (probably more than I needed to) to figure out the best way to write an update sql query that will dissallow duplicates on the column I am updating.
Meaning, if TableA.ColA already has a name 'TEST1', then when I'm changing another record, then I simply can't pick a value for ColA to be 'TEST1'.
It's pretty easy to simply just separate the query into a select, and use a server layer code that would allow conditional logic:
SELECT ID, NAME FROM TABLEA WHERE NAME = 'TEST1'
IF TableA.recordcount > 0 then
UPDATE SET NAME = 'TEST1' WHERE ID = 1234
END IF
But I'm more interested to see if these two queries can be combined into a single query.
I am using Oracle to figure things out, but I'd love to see a SQL Server query as well. I figured a MERGE statement can work, but for obvious reasons you can't have the clause:
..etc.. WHEN NOT MATCHED UPDATE SET ..etc.. WHERE ID = 1234
AND you can't update a column if it's mentioned in the join (oracle limitation but not limited to SQL Server)
ALSO, I know you can put a constraint on a column that prevents duplicate values, but I'd be interested to see if there is such a query that can do this without using constraint.
Here is an example start-up attempt on my end just to see what I can come up with (explanations on it failed is not necessary):
ERROR: ORA-01732: data manipulation operation not legal on this view
UPDATE (
SELECT d.NAME, ch.NAME FROM (
SELECT 'test1' AS NAME, '2722' AS ID
FROM DUAL
) d
LEFT JOIN TABLEA a
ON UPPER(a.name) = UPPER(d.name)
)
SET a.name = 'test2'
WHERE a.name is null and a.id = d.id
I have tried merge, but just gave up thinking it's not possible. I've also considered not exists (but I'd have to be careful since I might accidentally update every other record that doesn't match a criteria)
It should be straightforward:
update personnel
set personnel_number = 'xyz'
where person_id = 1001
and not exists (select * from personnel where personnel_number = 'xyz');
If I understand correctly, you want to conditionally update a field, assuming the value is not found. The following query does this. It should work in both SQL Server and Oracle:
update table1
set name = 'Test1'
where (select count(*) from table1 where name = 'Test1') > 0 and
id = 1234