SQL to update two columns in TABLE2 from TABLE1
I know this is a simple question for some of you, but I am new to SQLs, so please help...
I have two tables TABLE1 & TABLE2 as below, both tables contains more then 50million records:
SELECT * FROM TABLE1.
ID BUS_FID WORKID STATIONID
28400000117234 245 13461428.25 16520877.8
28400000117513 403 13461428.25 16520877.8
28400000117533 423 13461428.25 16520877.8
28400000117578 468 13461428.25 16520877.8
28400000117582 472 13461428.25 16520877.8
SELECT * FROM TABLE2.
BUS_FID ID TRPELID RELPOS WORKID STATIONID
114 28400000117658 28400000035396 23.225
115 28400000117659 28400000035396 23.225
116 28400000117660 28400000035396 23.225
117 28400000117661 28400000035396 23.225
118 28400000117662 28400000035396 23.225
119 28400000117663 28400000035396 23.225
120 28400000117664 28400000035396 23.225
121 28400000117665 28400000035396 23.225
122 28400000117666 28400000035396 23.225
123 28400000117667 28400000035396 23.225
124 28400000117668 28400000035396 23.225
125 28400000117669 28400000035396 23.225
126 28400000117670 28400000035396 23.225 Now I tried to use following SQL to update WORKID & STATIONID columns in TABLE2 but failed. BUS_FID in both tables have been UNIQUE indexed and they can be used as primary keys to join these two tables.
UPDATE (
SELECT p.WORKID px,
p.STATIONID py,
p.BUS_FID pid,
temp.WORKID tempx,
temp.STATIONID tempy,
temp.BUS_FID tempid
FROM TABLE1 temp,
TABLE2 p
WHERE pid = tempid
SET px = tempx,
py = tempy;
COMMIT;with above code, Oracle returned following errors:
SQL Error: ORA-00904: "TEMPID": invalid identifier
00904. 00000 - "%s: invalid identifier"Can anyone help me to correct it? Thanks~~~
BTW, both two tables contains over 50 million records. So, if you have a better SQL to perform the same task, please let me know!
Appreciated your help at advance.
Hi,
984210 wrote:
Tried to change to
p.bus_fid = temp.bus_fidit start running.
Can anyone please explain to me why this is happening? Thanks!!Column aliases (such as pid and tempid in your statement) can't be used in the same query in which they are defined (except in an ORDER BY clause). Elsewhere, you have to refer to the columns by their actual names.
Similar Messages
-
From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?
Hi,
Use NVL or COALESCE:
NVL (col_a, col_b)
Returns col_a if col_a is not NULL; otherwise, it returns col_b.
Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
HI can we update two columns at a time by regular update by mentioning two where clauses with respect to the columns
just need to put a comma between the fields to update them at the same time
update emp e1
set e1.ename=upper(e1.ename), e1.sal=(select avg(e2.sal) from emp e2 where e2.deptno=10 group by e2.deptno)
where e1.deptno=10;cheers ^^.
PS: at least in the example you have written.
PS2: sorry didnt put Edited by: Anaita on 31-ene-2011 1:58 -
How to update two columns in two tables?
hi friends
I have two tables linked to each other through SaleNo and SaleDT. their structure as below
Sales Table============
SaleNo int PK auto increment
SaleDT Datetime PK
Qnty decimal
Units decimal
Invoices table
=================InvoiceNo int PK Auto incremented
InvoiceDT Datetime
SaleNo int FK
SaleDT Datetime FK
Note that SaleDT column is NOT assigned with getDate() expression.
1. what I need to do is update the SaleDT column of Sales table and Invoices table with the value '2013-01-31 10:31:55.813', how do I do this without manually breaking the link between the tables?
2. Assume SaleNos 15 to 27 needs update the SaleDT to '2013-06-12 10:31:55.813', how do I do this complex operation where I I have update SaleDt column of two table of SaleNo range from 15 to 27?
thanks
I use Visual studio 2012 Ultimate and SQL server 2008 developer edition!Why not below? May be you will not be able to change your design now, but just want to share.
Sales Table============
SALEID int PK autoincrement
SaleNo int
SaleDT Datetime
Qnty decimal
Units decimalUNIQUE (Saleno,SaleDT)
Invoices table
=================InvoiceNo int PK Auto incremented
InvoiceDT Datetime
SALEID int FK -
HTML-DB 1.6 SQL Query (Concatenate two columns)
Hi everyone,
My query look like this. But I got this message
ORA-01403: no data found
Sql query(.....returning ... sql
What I can do ? I want to concatenate my two columns in one.
<pre>
-----Résultats de la recherche
BEGIN
DECLARE
requete varchar2(5000);
v_code_type varchar2(2000);
v_ordre varchar2(500);
BEGIN
:P1_NOM_BENEFICIAIRE := REPLACE(:P1_NOM_BENEFICIAIRE,' ', '%');
:P1_NOM_BENEFICIAIRE := REPLACE(:P1_NOM_BENEFICIAIRE,'-', '%');
requete := 'SELECT
(FEUI.NOM_BENEFICIAIRE || ''--'' || FEUI.PRENOM_BENEFICIAIRE) ABC,
FEUI.VALEUR_ID_BENEFICIAIRE,
FEUI.MONTANT,
FEUI.CODE_TYPE_DECLARATION,
FEUI.ANNEE_FISCALE,
FEUI.CODE_ENTITE,
FEUI.ID_FEUILLET_IMPOT,
FEUI.ID_AMENDEMENT,
FEUI.NO_RELEVE_ORIGINAL_PROV,
FEUI.ACRONYME_ID_BENEFICIAIRE,
TYPD.SIGNIFICATION
FROM
S29_FEUILLET_IMPOT FEUI,
S29_TYPE_DECLARATION TYPD
WHERE
(TYPD.CODE = FEUI.CODE_TYPE_DECLARATION) AND
(ANNEE_FISCALE = :P1_ANNEE_FISCALE) AND
(CODE_ENTITE LIKE ''%'' || SUBSTR(:P1_CODE_ENTITE,1,3) || ''%'') OR
(CODE_ENTITE = SUBSTR(:P1_CODE_ENTITE,1,3))
AND
((:P1_NAS IS NULL) OR (:P1_NAS = VALEUR_ID_BENEFICIAIRE))
AND
((:P1_NEQ IS NULL) OR (:P1_NEQ = VALEUR_ID_BENEFICIAIRE))
AND
((:P1_NOM_BENEFICIAIRE IS NULL) OR
((UPPER(NOM_BENEFICIAIRE) || UPPER(PRENOM_BENEFICIAIRE))
LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
((UPPER(PRENOM_BENEFICIAIRE) || UPPER(NOM_BENEFICIAIRE))
LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
((UPPER(RAISON_SOCIALE_LIGNE_1) || UPPER(RAISON_SOCIALE_LIGNE_2))
LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
((UPPER(RAISON_SOCIALE_LIGNE_2) || UPPER(RAISON_SOCIALE_LIGNE_1))
LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
(UPPER(SUBSTR(COORDONNEE_BENEFICIAIRE_SYGBEC,1,80))
LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'')
IF (:P1_CODE_RELEVE = 'A') OR
(:P1_CODE_RELEVE = 'M') OR
(:P1_CODE_RELEVE = 'C') THEN
v_code_type := '(
(FEUI.CODE_TYPE_DECLARATION = ''A'') OR
(FEUI.CODE_TYPE_DECLARATION = ''M'') OR
(FEUI.CODE_TYPE_DECLARATION = ''C'')
else
v_code_type :=
(:P1_CODE_RELEVE = CODE_TYPE_DECLARATION) OR
(:P1_CODE_RELEVE = ''%'')
end if;
WWV_FLOW.DEBUG('V_CODE_TYPE EST EGALE A :' || v_code_type);
v_ordre := 'ORDER BY NOM_BENEFICIAIRE, VALEUR_ID_BENEFICIAIRE,
ID_FEUILLET_IMPOT, ID_AMENDEMENT';
requete := requete || ' AND ' || v_code_type || v_ordre;
RETURN requete;
END;
END;
</pre>
Thanks. ByeThank you Scott,
I'm sorry, I should present you a reduce sql command.
I had construct my "long" sql command without concatenation. But, I decide to add a column just beside the other column.
After sending my message on OTN, I tried something else, I decided to copy my sql command without concatenation in an other region. I changed my sql command in the new region by adding my new column and this ''--'' and it works very well. Sometimes, It's really difficult to understand why it doesn't.
Thanks. Bye, -
Percentage calculation in t-sql based on two columns
Hi All
I have a source table with 4 columns and data like this..
ID Cnt Col1 Col2
1 22 17 5
2 20 15 5
3 12 5 7
4 10 null 10
5 25 25 null
My output should look like this..
ID Cnt Col1 Col2 Col1% Col22%
1 22 17 5 77.27 22.73
2 20 15 5 75.00 25.00
3 12 5 7 41.66 58.34
4 10 10 0 100
5 25 25 100 0
Create Statement:
CREATE TABLE [dbo].[Sample] (
[ID] Int NOT NULL,
[Cnt] Int NULL,
[Col1] Int NULL,
[Col2] Int NULL,
CONSTRAINT [Sample] PRIMARY KEY CLUSTERED
[ID] ASC
Insert Statement:
insert into Sample(ID, cnt,Col1, col2) values (1 , 22 , 17 , 5 )
insert into Sample(ID, cnt,Col1, col2) values (2 , 20 , 15 , 5 )
insert into Sample(ID, cnt,Col1, col2) values (3 , 12 , 5 , 7 )
insert into Sample(ID, cnt,Col1, col2) values (4 , 10 , null , 10 )
insert into Sample(ID, cnt,Col1, col2) values (5 , 25 , 25 , null)
Right now I am using below SQL but % fields are not coming correct.
Select (COUNT(CASE WHEN (col1-col2)) < 1) THEN -1 END) /COUNT(*) * 100) AS Col1%
,(COUNT(CASE WHEN (col1-col2) >=1) THEN 1 END) /COUNT(*) * 100) AS Col2%
I need SQL to get correct values in col1% and col2%
Thanks,
RH
sqlIs it what you need:
SELECT Id
,cnt
,col1
,col2
,CASE
WHEN Col1 IS NULL
OR Col1 = 0
THEN 0
ELSE CAST((col1 * 100.0) / cnt AS DECIMAL(10, 2))
END AS [Col1%]
,CASE
WHEN Col2 IS NULL
OR Col2 = 0
THEN 0
ELSE CAST((col2 * 100.0) / cnt AS DECIMAL(10, 2))
END AS [Col2%]
FROM Sample
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Help needed in PL/SQL for updating the column for multiple records
Hi,
I am new to PL/SQL and need some help. What is the most effiecient way to update some field in a table as I may need to update thousands of records. I have a coulmn groupid can have multiple records tied to it. All the records attached to some groupid have a priority field also.
How can I update the prorityfield value for all the groupids in a profiecient way. Here is a sample data
GroupId Priority
1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
3 1Here I have three groups 1, 2, 3. Now if any group contains only one record the priority remains same e.g. groupid=3 on top. If any group contains more than one record e.g. groupid=1 & 2 I want to re-arrange the priority fields e.g. If I want to update groupid=1 now if I change the priority of 2 to 5 (make it the last) I want to rearrange the remaing records priority i.e. if 2 becomes 5 as I have 5 rows for groupid=1 then 5 becomes 4, 4 becomes 3, 3 becomes 2 and 1 remains the same.
Same wya if I want to make the priority 1 to 3 for groupid=2 then need 2 to become 1 and 3 to become 2 etc....
Any help is appreciated.
ThanksHi,
You don't need PL/SQL to do this (though you can put the following in PL/SQL if you want to):
UPDATE table_x
SET priority = CASE
WHEN groupid = 1
AND priority = 2
THEN 5
WHEN groupod = 1
AND priority BETWEEN 3 AND 5
THEN priority - 1
WHEN groupid = 2
THEN
CASE
WHEN prioity = 1
THEN 3
ELSE priority - 1
END
END
WHERE groupId IN (1, 2)
AND ( priority BETWEEN 2 AND 5
OR groupid = 2
);There are lots of different techniques that can reduce your coidng: for example, the nested CASE statement used for groupid=2 above.
You could do several smaller UPDATEs (for example, one just for groupid=1). Execution will be slower, but coding and testing will be faster.
You could make the "magic numbers" 2 (for groupid=1) and 1 (for groupid=2) variables, even outside of PL/SQL.
If you need more help, post the information that Satyaki requested. -
Problem to update two different data targets from same DSO using DTP
Hi All,
I am trying to upload data from standard DSO 0FIA_DS11 to DSOs 0FIA_DS12 and 0FIA_DS13 using DTP.
I run DTP 0FIA_DS11 -> 0FIA_DS12 and all data is updated on target, but when I run DTP 0FIA_DS11 -> 0FIA_DS13 job stops at data source extraction, endless.
Is there something I missing with new 7.0 approach?
Could someone help me with this problem?!
Any help is welcome!
Thanks in advance,
AlexI'm loading cumulative/planned transactions from 0FI_AA_11 to 0FIA_DS11 just filtering by depreciation area on data package. Data is being successfully load and activated into this data provider.
From 0FIA_DS11 to 0FIA_DS12 I am loading data without filtering and load is finishing successfully.
From 0FIA_DS11 to 0FIA_DS13 I am not using any filter on DTP. I'm removing data with transaction type 'PLN' into start routine, but load is not even achieving this point. It stops during data source extraction.
Any more ideas?
Thanks for your previous reply!! -
Update a column with info from columnA, and if not in columnA, then columnB
I have a situation where I have to update a columnC with information stored one of 2 ways. It is stored one way in ColumnA, and another way in columnB. I must check the string if it is in columnA first, and if it is, that value will go in columnC to be updated. If it is not, I must go on to columnB and find it there. It will be in one of the 2 columns but I must use the way it is stored in these columns to store in my columnC to be updated. The data is basically turned around (not reversed letter for letter, though) in the 2 columns and must be stored the way it is found in columnA or columnB. Any ideas?
It's that simple? It will look in both columns this way? Now, I actually mentioned UPDATE when I meant INSERT, so I am doing this in a VALUES clause? Will I just use the phrase 'nvl(A, B);'?
-
Update one column while getting the value in another column
Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.
jsun wrote:
Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.Two statements != two database calls.
At least not in terms of SQL.
JDBC requires a 'statement' but in SQL (depending on the data source) that can include multiple statements. An obvious example of this is a stored proc but there are other ways as well. -
UPDATE COLS OF ONE TABLE FROM VALUES OF CERTAIN COLU OF ANOTHER TABLE
I have two tables table1 table1
(col1, (col1,
col2, col2,
col3, col3,
col4, col4,
timeperiod) timeperiod)
both have same column names. table1 has data for certain timeperiod. table2 also has the data for the same timeperiod. table2 has the correct data for col1, col2. I want to update the columns (col1, col2) in table1 with data from columns (col1, col2) in table2
and leave the col3, col4 in table1 untouched (no change). Each time I might have to update different columns. some tables have more than 20 columns. This is like, I need to update whatever field I want.
How do I do this with a script or block declaring variables. How do I control the update for certain columns. This is not a one time thing which I will be doing. I have to do this for several tables whenever the data is not right.
Thank you,
svHi ,
you can use MERGE for this kind of situations....here i have given some samples...refer this...
MERGE INTO bonuses D
USING (SELECT employee_id, salary, department_id FROM employees
WHERE department_id = 80) S
ON (D.employee_id = S.employee_id)
WHEN MATCHED THEN UPDATE SET D.bonus = D.bonus + S.salary*.01
WHEN NOT MATCHED THEN INSERT (D.employee_id, D.bonus)
VALUES (S.employee_id, S.salary*0.1);
By this way u can update any no. of columns...I hope this will help you...
Thanks
Raj -
How can update two rows in one query?
How can update two rows in one query?
Edited by: OracleM on May 4, 2009 12:16 AMWhat do you mean with "two rows"? May be two columns??
If the where clause of UPDATE query matches two rows, then it will update two rows. If you want to update two columns, then add column names to your query
UPDATE your_table SET col1=value1, col2=value2 WHERE your_where_clause- - - - - - - - - - - - - - - - - - - - -
Kamran Agayev A. (10g OCP)
http://kamranagayev.wordpress.com
[Step by Step install Oracle on Linux and Automate the installation using Shell Script |http://kamranagayev.wordpress.com/2009/05/01/step-by-step-installing-oracle-database-10g-release-2-on-linux-centos-and-automate-the-installation-using-linux-shell-script/] -
Need to update column in table from joining the two tables
Hi
i want to update a table by joining two table but i m getting the below error
single row subquery returns more than one value.
i m using following query
update table2
set deposite_date=(select a.deposit_date from table1 a,table2 b
where a.ban=b.ban and (a.deposit_date between b.cy_start_date and b.due_date))
table2
ban due_date cy_start_date deposite_date
100 5/6/2011 22/05/2011
101 7/11/2011 22/05/2011
102 5/25/2011 22/05/2011
table1
ban deposit_date
100 04/12/2011
100 04/15/2011
102 03/25/2011
101 04/26/2011
101 05/06/2011
101 07/26/2011
can i insert latest deposit_date from table1 which lies between b.cy_start_date and b.due_date
ThanksHi,
Welcome to the forum!
876466 wrote:
Hi
i want to update a table by joining two table but i m getting the below error
single row subquery returns more than one value.Exactly!
( SELECT a.deposit_date
FROM ...returns all deposit_dates.
( SELECT MAX (a.deposit_date)
FROM ...would return only the latest one.
Also, you need to correlate the sub-query to the main query, so that it only looks for rows with the same ban.
i m using following query
update table2
set deposite_date=(select a.deposit_date from table1 a,table2 b
where a.ban=b.ban and (a.deposit_date between b.cy_start_date and b.due_date))
table2
ban due_date cy_start_date deposite_date
100 5/6/2011 22/05/2011
101 7/11/2011 22/05/2011
102 5/25/2011 22/05/2011
table1
ban deposit_date
100 04/12/2011
100 04/15/2011
102 03/25/2011
101 04/26/2011
101 05/06/2011
101 07/26/2011
can i insert latest deposit_date from table1 which lies between b.cy_start_date and b.due_datePerhaps you need something like this:
UPDATE table2 b
SET deposit_date =
( SELECT MAX (a.deposit_date)
FROM table1 a
WHERE a.ban = b.ban
AND a.deposit_date BETWEEN b.cy_start_date
AND b.due_date
;Notice that table1 is the only table in the FROM clause of the sub-query, but the sub-query is correlated to table2, so we can reference columns from table2 in the sub-query.
Whenever you have a problem, post CREATE TABLE and INSERT statements for your sample data.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
If you're asking about a DML statement, such as UPDATE, the CREATE TABLE and INSERT statements should re-create the tables as they are before the DML, and the results will be the contents of the changed table(s) when everything is finished.
Always say which version of Oracle you're using.
Edited by: Frank Kulash on Aug 1, 2011 1:58 PM -
SQL update one column from another column
I'm looking for a way to update a SQL column with a portion
of info from another column in the same table.
example of a sql command
UPDATE table1
SET table1.columnname1 = table1.columnname2
FROM table
WHERE blah blah blah
Here's the thing... I only need a portion of the data found
in the source column. I'm not sure how I would do this then.
for example, the database has countries and states combined
into one column like this 'US-DC', 'US-CA', US-FL', etc. I want to
separate these into two columns, a country column and a state
column.... and I dont want to go though all the results and do this
line by line. How would I write the SQL command so that it puts
just the country in the country column, and puts just the state in
the state column, and it omits the dash all together.
any ideas?It depends. Are you using PHP and mySQL or ASP and SQL?
If you are using mysql and PHP you could use the following
code to loop through all records in your datatbase.
$sql="SELECT * FROM tablename"; //SET tablename to the name
of your database table.
$result=mysql_query($sql)or die(mysql_error(). " - $sql");
for($x = 0; $row=mysql_fetch_assoc($result); $x++){
//set up the variables from the table
$ID=$row['ID']; //this is the primary key
$var1=$row['contrystatecolumn']; //this is the name of the
column which holds the country-state
$var2=explode("-", $var1); //now we explode the string to get
the country and the state seperated and place the results into an
array
$country=$var2[0]; //this is the first piece of the exploded
string in the array
$state=$var2[1]; //this is the second piece of the exploded
string in the array
//now we update the database record with the new information
//remember to replace the tablename with your actual table
name and the columns country and state with the acutal names of
your columns in your table
$sql2="UPDATE tablename SET country='$country'.
state='$state' WHERE ID='$ID'";
$result2=mysql_query($sql2)or die(mysql_error() . " -
$sql2");
This code will loop through every record in your table and do
what you want very quickly.
Hope this helps
Stan Forrest
Senior Web Developer
ATG Internet -
Update SAME column name in two tables from ONE query
Dear All Seniors
Please tell me is it possible to update a same column name in two tables.
I have two tables in same schema
(1)table name
pem.igp_parent
column name
igp_no.
igp_type
(2)table name
pem.igp_child
column name
igp_no.
igp_type
i want to update igp_no column in one query please tell me how it would be possible.
thanks
yassenYou want to update the data from what to what? Where is the new data coming from?
If you are trying to put the same data in two different tables, that strongly implies that you have a normalization problem that needs to be addressed.
Why do you want a single query rather than updating each table in turn? Can you join the two target tables to produce a key-preserved view?
Justin
Maybe you are looking for
-
Redirecting all pages from old URL to index page of new URL
Hello everybody.. I have an Apache configuration question, can't work out the procedure in Server Admin. Basically I have a website at "oldurl.com". In Server Admin, I have the site set to serve a PHP file which runs a 301 redirect to "newurl.com". W
-
Purchase Order quantity is rounding off in Print out
HI ALL, In the Purchase Order quantity is rounding off while taking print out. I gave the quantity 10.450 LIT and it is rounding off to 10 LIT and if I gave 10.560 LIT is rounding off 11 LIT while taking print out. I am thinking some note we have to
-
How to change the Server email sender's name
We send email alerts from B1, but when they come from the system they go out with the return address of the email placed in the company details e-mail adress. This is OK but the Name that goes to the recipient says 'Server', Is there any way to chang
-
Quetion related to dbms_lob package
i have created the following procedure: create or replace procedure temp_clob as num clob; amount number; offset number; output varchar2(10); begin amount:=10; offset:=1; select data1 into num from test_clob where id1=1; dbms_lob.read(num,amount,offs
-
Unit not created in language EN
Hello, When loading a flat file, I receive the following error: Error in conversion exit CONVERSION_EXIT_CUNIT_INPUT So then I checked the units of measure in my flat file against the T006A table via SE16 in BW. When I looked up some of the units of