Left join with sub query - sql

Not sure why its throwing an error at t2. I am trying to run a simple sql query.
Running on MS-SQL and the error message says 'incorrect syntax near t2'
UPDATE t1
SET t1.EmpSubCompetency = t2.EmpSubCompetency,
t1.Competency = t2.Competency,
t1.FileName = t2.FileName,
t1.Longitude = t2.Longitude,
t1.Latitude = t2.Latitude,
t1.SubAreaName = t2.Region,
t1.SectorTag=t2.SectorTagClassification
FROM dbo.STG_MyCompetencies t1
LEFT JOIN (select * from dbo.STG_EmployeeMaster where Act_Flg='Y') t2

Your problem is the missing ON clause. Further, you don't need a subquery for this logic:
FROM dbo.STG_MyCompetencies t1 LEFT JOIN
dbo.STG_EmployeeMaster t2
ON t1.??? = t2.??? AND
em.Act_Flg = 'Y'
Note that unmatched rows will have all the columns set to NULL.
The ??? is for whatever column should be used for the JOIN.

Related

UPDATE statement with multiple joins to main table in PostgreSQL

I'm doing conversation from mysql to postgres.
I try to update table EUTMPDFHDT T with join table EUTMPDFH T1 and EUTMPTBLDT T2.
Here is code what I use in mysql.
UPDATE EUTMPDFHDT
SET NWCOLID=T2.NWCOLID
FROM EUTMPDFHDT T
INNER JOIN EUTMPDFH T1 ON T.DFHID = T1.DFHID AND T1.DFHTYP IN ('D','U','S','P','B')
INNER JOIN EUTMPTBLDT T2 ON T.COLID = T2.COLID
In postgres I did try to follow this UPDATE statement with multiple joins in PostgreSQL
But to no avail I cannot solve it because the update statement is not same.
Here what have I done in postgres:
UPDATE EUTMPDFHDT AS T
SET NWCOLID=T2.NWCOLID
FROM
EUTMPDFH T1
JOIN EUTMPTBLDT T2 ON T.COLID = T2.COLID
WHERE T.DFHID = T1.DFHID AND T1.DFHTYP IN ('D','U','S','P','B');
Here is the error that I hit
ERROR: invalid reference to FROM-clause entry for table "t"
LINE 5: JOIN EUTMPTBLDT T2 ON T.COLID = T2.COLID
^
HINT: There is an entry for table "t", but it cannot be referenced from this part of the query.
QUERY: UPDATE EUTMPDFHDT AS T
SET NWCOLID=T2.NWCOLID
FROM
EUTMPDFH T1
JOIN EUTMPTBLDT T2 ON T.COLID = T2.COLID
WHERE T.DFHID = T1.DFHID AND T1.DFHTYP IN ('D','U','S','P','B')
As documented in the manual you should not repeat the target table in the FROM clause of an UPDATE statement.
The FROM clause for an UPDATE unfortunately doesn't follow the exact same rules as the one used in the SELECT clause. It's easier to use the old implicit joins instead of the (usually preferred) explicit JOIN operators.
As far as I can tell this is what you are looking for:
UPDATE eutmpdfhdt as t
SET nwcolid = t2.nwcolid
FROM eutmpdfh t1,
eutmptbldt t2
WHERE t.dfhid = t1.dfhid
AND t.colid = t2.colid
AND t1.dfhtyp IN ('D','U','S','P','B')
You can't include a column from the table you want to update within the ON clause. It must be in the WHERE. If you modify your code like so, I believe it gets you the result you need:
UPDATE
EUTMPDFHDT AS T
SET
NWCOLID = T2.NWCOLID
FROM
EUTMPTBLDT T2
WHERE
T.COLID = T2.COLID AND
EXISTS (SELECT 1 FROM EUTMPDFH WHERE DFHID = t.DFHID AND DFHTYP IN ('D','U','S','P','B'));
You cannot reference the column of FROm table from ON clause in update query. You can chage the query as follows
UPDATE EUTMPDFHDT AS T
SET NWCOLID=Q.NWCOLID
FROM (SELECT T2.NWCOLID, T.DFHID
FROM EUTMPDFHDT AS T
JOIN EUTMPDFH T1 ON T.DFHID = T1.DFHID
JOIN EUTMPTBLDT T2 ON T.COLID = T2.COLID
WHERE T1.DFHTYP IN ('D','U','S','P','B'))Q
WHERE Q.DFHID=T.DFHID

Oracle sql MERGE INTO with a single where clause

I have the following SQL code (this is how much I've got so far):
MERGE INTO SCHEMA1.TABLE_1 table1 USING
(
SELECT DISTINCT table2.column1,
view1.column2
FROM SCHEMA2.TABLE_2 table2
LEFT JOIN SCHEMA2.VIEW_1 view1
ON table2.column2 = view1.column3
) t2 ON (table1.column3 = t2.column1 )
WHEN MATCHED THEN
UPDATE
SET table1.column4 = t2.column2;
The following is the definition of VIEW_1 :
CREATE VIEW SCHEMA_2.VIEW_1
AS (SELECT
SCHEMA_2.TABLE_1.COLUMN_1,
SCHEMA_2.TABLE_2.COLUMN_1,
SCHEMA_2.TABLE_2.COLUMN_2,
SCHEMA_2.TABLE_2.COLUMN_3,
SCHEMA_2.TABLE_5.COLUMN_1,
SCHEMA_2.TABLE_6.COLUMN_1,
SCHEMA_2.TABLE_6.COLUMN_2,
SCHEMA_2.TABLE_6.COLUMN_3,
SCHEMA_2.TABLE_6.COLUMN_4,
SCHEMA_2.TABLE_7.COLUMN_1,
SCHEMA_2.TABLE_7.COLUMN_2,
SCHEMA_2.TABLE_8.COLUMN_1
FROM SCHEMA_2.TABLE_1
INNER JOIN SCHEMA_2.TABLE_2
ON SCHEMA_2.TABLE_1.COLUMN_1 = SCHEMA_2.TABLE_2.COLUMN_2
INNER JOIN SCHEMA_2.TABLE_5
ON SCHEMA_2.TABLE_1.COLUMN_4 = SCHEMA_2.TABLE_5.COLUMN_3
LEFT OUTER JOIN SCHEMA_2.TABLE_6
ON SCHEMA_2.TABLE_2.COLUMN_2 = SCHEMA_2.TABLE_6.COLUMN_4
LEFT OUTER JOIN SCHEMA_2.TABLE_7
ON SCHEMA_2.TABLE_2.COLUMN_1 = SCHEMA_2.TABLE_8.COLUMN_5
);
But I'm getting the below error message:
Error report -
SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 - "unable to get a stable set of rows in the source tables"
*Cause: A stable set of rows could not be got because of large dml
What causes the error? Where to change in the code to make it work?
Thanks for helping out!
For this example your problem is definitely in the USING subquery. This query produces more than one value of table2.column1:
SELECT DISTINCT table2.column1,
view1.column2
FROM SCHEMA2.TABLE_2 table2
LEFT JOIN SCHEMA2.VIEW_1 view1
ON table2.column2 = view1.column3
So the ON clause will match the same row(s) in table1 more than once:
ON (table1.column3 = t2.column1 )
Oracle cannot figure out which value of t2.column2 should be used in the UPDATE, so it hurls ORA-30926.
Using distinct in the subquery doesn't help because that gives permutations of all the columns. You need to write a subquery which will produce unique values of t2.column1 across all rows, or add another identifying column(s) to generate a unique key you can join to table1.
In my experience, this error is returned, not only when the USING clause returns more than one row for a row in the MATCH table, but also frequently when it cannot be sure that only one row will be returned (even if there are no actual cases of multiple rows being returned). To force the parser to accept the query in cases like this, I usually resort to using a GROUP BY on the MATCH..ON column(s).
MERGE INTO SCHEMA1.TABLE_1 table1 USING
(
SELECT table2.column1,
MAX(view1.column2) as column2
FROM SCHEMA2.TABLE_2 table2
LEFT JOIN SCHEMA2.VIEW_1 view1
ON table2.column2 = view1.column3
GROUP BY table2.column1
) t2 ON (table1.column3 = t2.column1 )
WHEN MATCHED THEN
UPDATE
SET table1.column4 = t2.column2;

UPDATE on LEFT JOIN error

I have an SQL query which keeps giving me an error.
I have tried multiple ways of writing the query but I have had no luck in fixing it.
I have two tables(table1 and table2) with duplicate columns orgcodeold and orgcode. table1.orgcode is empty but table2.orgcode is populated.
I am trying to populate table1.orgcode with table2.orgcode where table1.orgcodeold=table2.orgcodeold.
THE ERROR
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'AS'.
THE QUERY
UPDATE table1 AS t1
LEFT JOIN table2 AS t2
ON t2.orgcodeold = t1.orgcodeold
SET t1.orgcode = t2.orgcode
WHERE t1.orgcodeold = t2.orgcodeold
Please help.
Well, you have almost the whole syntax wrong. It should be:
UPDATE t1
SET t1.orgcode = t2.orgcode
FROM table1 AS t1
INNER JOIN table2 AS t2
ON t2.orgcodeold = t1.orgcodeold;
This should work:
UPDATE t1
SET t1.orgcode = t2.orgcode
from table1 AS t1
LEFT JOIN table2 AS t2
ON t2.orgcodeold = t1.orgcodeold

SQL Error: Invalid object name 'Table name'

I have 2 tables as below:
tblTransaction
tblMobileRegistration
I want to join these 2 tables and count the numbers of raws that specific columns value in that is not '1' as below:
SELECT COUNT(Transaction_MobileErrorCode) FROM T1 WHERE Transaction_MobileErrorCode <> ''
Its my whole query:
SELECT
T1.*,
T2.*,
(SELECT COUNT(Transaction_MobileErrorCode) FROM T1 WHERE Transaction_MobileErrorCode <> '')
FROM
(SELECT MobileRegistration_DateTime, Transaction_MobileErrorCode FROM tblTransaction, tblMobileRegistration
WHERE T1.ID1 = T2.ID1 AND
T1.ID2 = '111111' AND
T1.ID3 = '222222' AND
T1.ID4 = '333333' AND
T1.ID5 = '444444') AS T1,
tblMobileRegistration AS T2
but I got this error:
Invalid object name 'T1'.
so how can I fix it?
thanks for any helping...
It is a bit hard to tell what results you actually want. But this following may do what you want:
SELECT MobileRegistration_DateTime, Transaction_MobileErrorCode,
SUM(CASE WHENTransaction_MobileErrorCode <> '' THEN 1 ELSE 0 END) OVER ()
FROM tblTransaction t JOIN
tblMobileRegistration mr
ON t.ID1 = mr.ID1
WHERE T1.ID2 = '111111' AND
T1.ID3 = '222222' AND
T1.ID4 = '333333' AND
T1.ID5 = '444444';
You should learn to use proper, explicit join syntax. You simply have too many table references for what you probably want to do.
This version uses a window function. You don't specify the database, but this is ANSI standard syntax supported by most databases.
This is your inner most query. Nothing is aliased as T1 (or T2). You are either mixing up your parenthesis, or missing aliases. If you're missing aliases, you really need to get a bit more creative than just using t1 and t2 everywhere. Makes debugging your query very difficult.
SELECT MobileRegistration_DateTime,
Transaction_MobileErrorCode
FROM tblTransaction,
tblMobileRegistration
WHERE T1.ID1 = T2.ID1 AND
T1.ID2 = '111111' AND
T1.ID3 = '222222' AND
T1.ID4 = '333333' AND
T1.ID5 = '444444'
As other folks have said, your query is very confusing. If you really are intending to have all those derived tables, break it down and build it from the inside out.
It was a runtime error.
At first it will checks all columns in select statement from tables but not the assigned table(T1 will created while executing and deleted after that execution)
remove that select statement (from t1) then execute it will work.
(SELECT COUNT(Transaction_MobileErrorCode) FROM T1)
from this line you are getting error

SQL command to compare results is not working [duplicate]

I want to update a column in a table making a join on other table e.g.:
UPDATE table1 a
INNER JOIN table2 b ON a.commonfield = b.[common field]
SET a.CalculatedColumn= b.[Calculated Column]
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
But it is complaining :
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'a'.
What is wrong here?
You don't quite have SQL Server's proprietary UPDATE FROM syntax down. Also not sure why you needed to join on the CommonField and also filter on it afterward. Try this:
UPDATE t1
SET t1.CalculatedColumn = t2.[Calculated Column]
FROM dbo.Table1 AS t1
INNER JOIN dbo.Table2 AS t2
ON t1.CommonField = t2.[Common Field]
WHERE t1.BatchNo = '110';
If you're doing something silly - like constantly trying to set the value of one column to the aggregate of another column (which violates the principle of avoiding storing redundant data), you can use a CTE (common table expression) - see here and here for more details:
;WITH t2 AS
(
SELECT [key], CalculatedColumn = SUM(some_column)
FROM dbo.table2
GROUP BY [key]
)
UPDATE t1
SET t1.CalculatedColumn = t2.CalculatedColumn
FROM dbo.table1 AS t1
INNER JOIN t2
ON t1.[key] = t2.[key];
The reason this is silly, is that you're going to have to re-run this entire update every single time any row in table2 changes. A SUM is something you can always calculate at runtime and, in doing so, never have to worry that the result is stale.
Try it like this:
UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a INNER JOIN table2 b ON a.commonfield = b.[common field]
WHERE a.BatchNO = '110'
Answer given above by Aaron is perfect:
UPDATE a
SET a.CalculatedColumn = b.[Calculated Column]
FROM Table1 AS a
INNER JOIN Table2 AS b
ON a.CommonField = b.[Common Field]
WHERE a.BatchNo = '110';
Just want to add why this problem occurs in SQL Server when we try to use alias of a table while updating that table, below mention syntax will always give error:
update tableName t
set t.name = 'books new'
where t.id = 1
case can be any if you are updating a single table or updating while using join.
Although above query will work fine in PL/SQL but not in SQL Server.
Correct way to update a table while using table alias in SQL Server is:
update t
set t.name = 'books new'
from tableName t
where t.id = 1
Hope it will help everybody why error came here.
MERGE table1 T
USING table2 S
ON T.CommonField = S."Common Field"
AND T.BatchNo = '110'
WHEN MATCHED THEN
UPDATE
SET CalculatedColumn = S."Calculated Column";
UPDATE mytable
SET myfield = CASE other_field
WHEN 1 THEN 'value'
WHEN 2 THEN 'value'
WHEN 3 THEN 'value'
END
From mytable
Join otherTable on otherTable.id = mytable.id
Where othertable.somecolumn = '1234'
More alternatives here.
Seems like SQL Server 2012 can handle the old update syntax of Teradata too:
UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
If I remember correctly, 2008R2 was giving error when I tried similar query.
I find it useful to turn an UPDATE into a SELECT to get the rows I want to update as a test before updating. If I can select the exact rows I want, I can update just those rows I want to update.
DECLARE #expense_report_id AS INT
SET #expense_report_id = 1027
--UPDATE expense_report_detail_distribution
--SET service_bill_id = 9
SELECT *
FROM expense_report_detail_distribution erdd
INNER JOIN expense_report_detail erd
INNER JOIN expense_report er
ON er.expense_report_id = erd.expense_report_id
ON erdd.expense_report_detail_id = erd.expense_report_detail_id
WHERE er.expense_report_id = #expense_report_id
Another approach would be to use MERGE
;WITH cteTable1(CalculatedColumn, CommonField)
AS
(
select CalculatedColumn, CommonField from Table1 Where BatchNo = '110'
)
MERGE cteTable1 AS target
USING (select "Calculated Column", "Common Field" FROM dbo.Table2) AS source ("Calculated Column", "Common Field")
ON (target.CommonField = source."Common Field")
WHEN MATCHED THEN
UPDATE SET target.CalculatedColumn = source."Calculated Column";
-Merge is part of the SQL Standard
-Also I'm pretty sure inner join updates are non deterministic..
Similar question here where the answer talks about that
http://ask.sqlservercentral.com/questions/19089/updating-two-tables-using-single-query.html
I think, this is what you are looking for.
UPDATE
Table1
SET
Table1.columeName =T1.columeName * T2.columeName
FROM
Table1 T1
INNER JOIN Table2 T2
ON T1.columeName = T2.columeName;
I had the same issue.. and you don't need to add a physical column.. cuz now you will have to maintain it..
what you can do is add a generic column in the select query:
EX:
select tb1.col1, tb1.col2, tb1.col3 ,
(
select 'Match' from table2 as tbl2
where tbl1.col1 = tbl2.col1 and tab1.col2 = tbl2.col2
)
from myTable as tbl1
Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.
--update clients table cell field from custom table containing mobile numbers
update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m
on c.Last_Name + c.First_Name = m.Name
Those who are using MYSQL
UPDATE table1 INNER JOIN table2 ON table2.id = table1.id SET table1.status = 0 WHERE table1.column = 20
Try:
UPDATE table1
SET CalculatedColumn = ( SELECT [Calculated Column]
FROM table2
WHERE table1.commonfield = [common field])
WHERE BatchNO = '110'