Update column based on sum of data from another table
Hi We had two tables.
Table 1: matusetrans
ITEMNUM Location Quantity transdate
AM1324 AM1 2 12-4-12
AM1324 AM1 2 15-5-12
AM1324 AM1 3 10-6-12
AM1324 AM1 4 5-1-13
AM1324 AM1 2 13-3-13
AM1324 AM2 3 2-5-12
AM1324 AM2 2 12-7-12
AM1324 AM2 1 13-2-13
Table 2: Inventory
ITEMNUM STORELOC lastyear currentyear
AM1324 AM1 need sum(quantity) here need sum(quantity)
AM1324 AM2 need sum(quantity) here need sum(quantity)
We have to update the last year and current year columns with sum of quantities for each item from matusetrans table based on date at different location in Inventory table.
we had nearly 13,000 records(itemnum's with different location) in inventory table in DB we have to update entire records.
Any help...How to write an sql queries to update lastyear and currentyear columns with sum of quantities based on itemnum and location in Inventory table
Thanks
Edit/Delete Message
Try this
SQL> select * from matusetrans;
ITEMNU LOC QUANTITY TRANSDATE
AM1324 AM1 2 12-APR-12
AM1324 AM1 2 15-MAY-12
AM1324 AM1 3 10-JUN-12
AM1324 AM1 4 05-JAN-13
AM1324 AM1 2 13-MAR-13
AM1324 AM2 3 02-MAY-12
AM1324 AM2 2 12-JUL-12
AM1324 AM2 1 13-FEB-13
8 rows selected.
SQL> select * from inventory;
ITEMNU STO LASTYEAR CURRENTYEAR
AM1324 AM1 0 0
AM1324 AM2 0 0
SQL> merge into inventory i
2 using (
3 select itemnum
4 , location
5 , sum(decode(extract(year from transdate), extract(year from sysdate), quantity)) currentyear
6 , sum(decode(extract(year from transdate), extract(year from add_months(sysdate, -12)), quantity)) lastyear
7 from matusetrans
8 group
9 by itemnum
10 , location
11 ) t
12 on (
13 i.itemnum = t.itemnum and
14 i.storeloc = t.location
15 )
16 when matched then
17 update set i.lastyear = t.lastyear
18 , i.currentyear = t.currentyear
19 /
2 rows merged.
SQL> select * from inventory;
ITEMNU STO LASTYEAR CURRENTYEAR
AM1324 AM1 7 6
AM1324 AM2 5 1
SQL>
Similar Messages
-
Update column based on a parsed value from another column
<p>i have table1 which has description, region and division columns. If the "description like '% (%.% or %.%'" I want to parse the first '%.%' which has the values for 'region.division' and update the table1.region
and table1.division columns. </p><p></p><p>FOR EXAMPLE</p><p>DESCRIPTION, REGION, DIVISION</p><p>Total Employes (SouthEast.Florida or 111.22),,</p><p>WANT IT AS</p><p>Total Employes (SouthEast.Florida
or 111.22),SouthEast,Florida</p><p>thanks in advance.</p><p></p>In my tests the following update of CTE works fine. Hopefully this will work for the real table as well although it is a good idea to always have primary key:
DECLARE @t TABLE (
DESCRIPTION VARCHAR(200)
,REGION VARCHAR(30)
,DIVISION VARCHAR(30)
INSERT INTO @t (
DESCRIPTION
,REGION
,DIVISION
VALUES (
'Total Employes (SouthEast.Florida or 111.22)'
'Test no info'
WITH cteParsed
AS (
SELECT *
,CASE
WHEN DESCRIPTION LIKE '%(%.%'
THEN substring(description, charindex('(', DESCRIPTION) + 1, len(Description))
ELSE NULL
END AS StartInfo
FROM @t
WHERE DESCRIPTION LIKE '%(%.%'
AND len(Region) = 0
AND len(Division) = 0
,cte
AS (
SELECT *
,substring(StartInfo, 1, charindex(' ', StartInfo) - 1) AS Rest
FROM cteParsed
UPDATE cte
SET region = substring(Rest, 1, charindex('.', Rest) - 1)
,division = substring(Rest, charindex('.', Rest) + 1, len(Rest))
SELECT *
FROM @t; -- verify the changes taken place
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Data from another table, to be displayed on table based screen
I have a block that is based on one table, if I found the record(s) on that table I will display it on the forms, No Problemo. But, if record(s) was not in the said table, I have to get the data on another table and then display it on the same forms. Is there someone who can show me how I can get the data from another table and display it on screen that is based on another table?
suppose you have 2 table emp_n and emp with same table structure
first check data from emp_n if not found then go to emp
try it:-
you will change block name at run time(query data source)
by
emp_n is old
emp is new
set_block_property('emp_n',QUERY_DATA_SOURCE_NAME,'emp');
if no data found in emp_n table then
change the block query name by
set_block_property('emp_n',QUERY_DATA_SOURCE_NAME,'emp');
in next try it will go to emp table for fetching record
kuljeet pal singh -
How to populate a table based on a row selection from another table.
Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
ganeshI understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
"EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
Hope this helps. -
Breakout table (fill table with matching data from another table)
Hi
I've been trying to study old discussions about breakout tables. I feel I'm close, but still no cigar :-)
In plain english, I'm trying to autocreate rows with data on a table, based on matching values from another table. E.g. have a table to display all rows where type = AssetX
I have attached a screenshot of my "master table" called Assets:
I'm looking to prefill Asset name, Total from this table and populate a new table called e.g. Greenhouse
Where I'd be adding more data (date, income, expense).
Any help whould be greatly appreciated.
Thanks!Hi,
Here is a Sample Query.
Update Emp A
Set Sal = (Select Sal from emp b where
a.empno = b.empno)
where empno in (select empno from emp);
Regards,
Ganesh R
null -
Deleting data from another table with multiple conditions
Hi frnds
I need to delete some data from a table based on multiple condition I tried following sql but its deleteing some rows which is not meeting the criteria which is really dangerours. When i trying = operator it returns ORa- 01427 single -row subquery returns more than one row
delete from GL_TXNS
where TRN_DT in (Select trn_Dt from GL_MAT)
and BR in (select ac_branch from GL_MAT)
and CODE in (select CODE T from GL_MAT)
and (lcy_amt in (select lcy_amt from GL_MAT) or
fcy_amt in(select fcy_amt from GL_MAT)
rgds
ramyaMy answer is the same as Avinash's but I will explain a little bit more.
ORa- 01427 single -row subquery returns more than one rowmeans that you have a subquery that Oracle is expecting one value from that is returning multiple values. In your case you need one value for the equijoin ("=") and you are getting more than one value back. The error happens even if all the values are the same - multiple values being returned will cause the error.
The solution is to either allow multiple values to be returned (say, use the IN condition istead of "=") or only return one value if possible (say, forcing one value by using DISTINCT, GROUP BY, or a WHERE clause condition of ROWNUM=1) - but these workarounds must be checked carefully to make sure they work correctkly -
Procedure to insert data into table by selecting data from another table
Hi all,
I have to create a procedure where i have to select the data from one table and insert it into another table. Any help on this. And i have to update the 2nd table also when ever new records got inserted in the 1st table then.
RegardsHi, you can try something like:
CREATE [OR REPLACE] PROCEDURE procedure_name
IS
BEGIN
INSERT INTO TABLE1
VALUES (SELECT * FROM TABLE2);
END;
For the other part you may create a trigger on the first table AFTER INSERT to insert the values in the second table too. -
Update query - updating data from another table.
I have the following tables and data
CREATE TABLE UPD_TEST1
T1_COL1 NUMBER(10),
T1_COL2 VARCHAR2(10 BYTE),
T1_COL3 VARCHAR2(10 BYTE)
INSERT INTO UPD_TEST1 ( T1_COL1, T1_COL2, T1_COL3 ) VALUES (
1, 'raji', 'sis');
INSERT INTO UPD_TEST1 ( T1_COL1, T1_COL2, T1_COL3 ) VALUES (
2, 'manju', 'sis');
INSERT INTO UPD_TEST1 ( T1_COL1, T1_COL2, T1_COL3 ) VALUES (
3, 'chinnu', 'sis');
COMMIT;
CREATE TABLE UPD_TEST2
T2_COL1 NUMBER(10),
T2_COL2 VARCHAR2(10 BYTE),
T2_COL3 VARCHAR2(10 BYTE)
INSERT INTO UPD_TEST2 ( T2_COL1, T2_COL2, T2_COL3 ) VALUES (
1, 'muralee', 'bro');
INSERT INTO UPD_TEST2 ( T2_COL1, T2_COL2, T2_COL3 ) VALUES (
2, 'manoj', 'bro');
INSERT INTO UPD_TEST2 ( T2_COL1, T2_COL2, T2_COL3 ) VALUES (
3, 'manoop', 'bro');
COMMIT;
I need to update the columns of UPD_TEST1 with some values from UPD_TEST2 based on some conditions.
i wanted to update multiple rows at a time.Can it be done using one query..
Anyone please help me.
I have dome some search and got the following query but it can update only one record at a time
UPDATE upd_test1
SET ( t1_col2,t1_col3) =(SELECT t2_col2,t2_col3 FROM upd_test2 WHERE t2_col1 =2)
the following query won't work
UPDATE upd_test1
SET ( t1_col2,t1_col3) =(SELECT t2_col2,t2_col3 FROM upd_test2 WHERE t2_col1 IN (2,3))
ORA-01427: single-row subquery returns more than one row
I wanted to update multiple records at a timebit weird approach though, but you could try merge
SQL> Select * From Upd_Test1;
T1_COL1 T1_COL2 T1_COL3
1 raji sis
2 manju sis
3 chinnu sis
SQL> Merge Into Upd_Test1 A Using Upd_Test2 B
2 On (a.T1_Col1 = b.T2_Col1 and b.t2_col1 in (2,3))
3 When Matched Then
4 Update Set
5 A.T1_Col2 = B.T2_Col2
6 ,a.T1_Col3 = b.T2_Col3;
2 rows merged.
SQL> Select * From Upd_Test1;
T1_COL1 T1_COL2 T1_COL3
1 raji sis
2 manoj bro
3 manoop broVivek L -
Populating table with data from another table with fewer columns
Hi,
I have 2 tables:
Table 1:
Column 1
Column 2
Column 3
Table 2:
Column 1
Column 2
I want to populate Table 1 with all the data from Table 2, and populate Column 3 of Table 1 with numbers from a sequence. Is there a SQL stmt to do this? If not, what is the best way to do it in PL/SQL?
Thank you
ShailanCREATE SEQUENCE t1_seq
START WITH 1
INCREMENT BY 1
CACHE 100;
INSERT INTO t1( col1, col2, col3 )
SELECT col1, col2, t2_seq.nextval
FROM t2Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Updating a portlet's content with data from another portlet
hi,
I have two portlets. The first portlet has a form that collects data from the
user to process a query. Once the query gets processed, i want to display the
query results on the second portlet. How do i go about doing this?
Thanks in advanceyou could start by reading other posts in this newsgroup addressing the exact same
topic. also, look at martini portlet on dev2dev.bea.com
"rashed karim" <[email protected]> wrote:
>
hi,
I have two portlets. The first portlet has a form that collects data
from the
user to process a query. Once the query gets processed, i want to display
the
query results on the second portlet. How do i go about doing this?
Thanks in advance -
Using a caculated field to get data from another table.
I have a Products Table that I need to add a field to. This field gains data from a Supplier table by using the supplier code to find the correct supplier type. All Products have a Supplier Code. So for example in SQL this would be a simple where statement looking something like this.
SELET Supplier.Type
From Supplier , Product
Where Supplier.Code = Product.SupplierCode
And ProductID = someID
How would you write this as a caculated field in MDM?Hi Chauncey
My previous post seems to have disappeared into the ether, so here it is again.
If you only want to do this linking for display purposes, then consider the following possibility:
The main Products table has a field which looks up to the flat table Suppliers. The flat table Suppliers has a field that either A) looks up to a flat SupplierTypes table or B) is a normal field in which the supplier type is stored. Inside the flat Suppliers table, just set both the SupplierCode and SupplierType fields to be display fields. MDM will automatically display both pieces of data inside the single field in the Products table.
If you need the SupplierType in a separate field then you cannot do this with an expression (calculation or assignment.) You'll need to write a piece of code using one of the MDM APIs in order to do this lookup.
HTH,
Mark -
Updating a table with data from another table with joins involving 3 other
update party_relship pr
set pr.COMMENT_TEXT = temp.notes
from party p,
party p1,
party_reference pref,
TEMP_DEPT_NOTE temp
where pr.FROM_PARTY_ID = p.PARTY_ID
and p.CMA_CUSTOMER_NUMBER = temp.cma_num
and pr.TO_PARTY_ID = p1.PARTY_ID
and p1.PARTY_ID = pref.PARTY_ID
and pref.REFERENCE_VALUE = temp.deptnum
ORA-00933: SQL command not properly ended
What is the problem here.
Thanks !There are a few issues here 1) no from clause is directly part of the update stmt,
2) temp.notes is not available directly
I am not 100% sure this update is correct since I am selecting temp.notes using the same query as the in the where clause but I wanted to show the complete syntax. Basically if you need to limit the number of updates done then change the select that is part of the exists clause, if you need to change the way the pr.comment_text is being set then to need to change the sub_query.
update party_relship pr
set pr.comment_text =
(select temp.notes
from party p,
party p1,
party_reference pref,
temp_dept_note temp
where pr.from_party_id = p.party_id
and p.cma_customer_number = temp.cma_num
and pr.to_party_id = p1.party_id
and p1.party_id = pref.party_id
and pref.reference_value = temp.deptnum)
where exists(select 1
from party p,
party p1,
party_reference pref,
temp_dept_note temp
where pr.from_party_id = p.party_id
and p.cma_customer_number = temp.cma_num
and pr.to_party_id = p1.party_id
and p1.party_id = pref.party_id
and pref.reference_value = temp.deptnum)Message was edited by:
Bob C -
Update a table with data from another table
Hi to All,
I have in my 'schema' 2 tables:
CREATE TABLE T_ITEMS
ITEM_GROUP VARCHAR2(10 BYTE) NOT NULL,
ITEM_CODE VARCHAR2(25 BYTE) NOT NULL,
ITEM_DESCRIPTION VARCHAR2(40 BYTE) NOT NULL,
ITEM_QTA NUMBER(16,4),
ITEM_PRICE NUMBER(18,5)
TABLESPACE DOM8DATI
PCTUSED 0
PCTFREE 10
INITRANS 1
MAXTRANS 255
STORAGE (
INITIAL 2M
MINEXTENTS 1
MAXEXTENTS 2147483645
PCTINCREASE 0
BUFFER_POOL DEFAULT
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;
CREATE TABLE T_PRICES
ITEM_GROUP VARCHAR2(10 BYTE) NOT NULL,
ITEM_CODE VARCHAR2(25 BYTE) NOT NULL,
ITEM_PRICE NUMBER(18,5)
TABLESPACE DOM8DATI
PCTUSED 0
PCTFREE 10
INITRANS 1
MAXTRANS 255
STORAGE (
INITIAL 2M
MINEXTENTS 1
MAXEXTENTS 2147483645
PCTINCREASE 0
BUFFER_POOL DEFAULT
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;
I need to create a script that for each record in T_ITEMS, read if exist the code (ITEM_GROUP,ITEM_CODE) in T_PRICES and update ITEM_PRICE in T_ITEMS.
Can anyone help me?
Thank You and Best Regards
GaetanoMERGE INTO T_ITEMS B USING (
SELECT
ITEM_GROUP ,
ITEM_CODE,
ITEM_PRICE
FROM T_PRICES) E
ON (B.ITEM_CODE= E.ITEM_CODE)
WHEN MATCHED THEN
UPDATE SET B.ITEM_PRICE= E.ITEM_PRICE
WHEN NOT MATCHED THEN
INSERT (ITEM_GROUP ,
ITEM_CODE,
ITEM_DESCRIPTION ,
ITEM_QTA ,
ITEM_PRICE )
VALUES (E.ITEM_GROUP,
E.ITEM_CODE,
'UNKNOWN',
'UNKNOWN',
E.ITEM_PRICE);
COMMIT; -
How to insert subtype data from another table in a object table ?
Hi all
I have been looking at the differences answers there are about insert data form a subtype in a object table of a supertype ,but have not found a solution yet.
I hope you can help me.
I my code Action_Logs is the object table and CloseStore_Logs_t is a subtype of Action_Logs_t
My code is
insert into Action_Logs(CloseStore_Logs_t (action_logs_id , physicalstores.physicalstores_id , brandedstores.BRANDEDSTORES_ID ,physicalstores.COMPANIES_ID ,brandedstores.CREATED_BY ,
brandedstores.CREATED_DATE , brandedstores.DELETED ,brandedstores.CLOSED_DATE as brandedstore_closedate,
physicalstores.CLOSED_DATE as physicalstore_closedate)
select CloseStore_Logs_t((null as action_logs_id , physicalstores.physicalstores_id , brandedstores.BRANDEDSTORES_ID ,physicalstores.COMPANIES_ID ,brandedstores.CREATED_BY ,
brandedstores.CREATED_DATE , brandedstores.DELETED ,brandedstores.CLOSED_DATE as brandedstore_closedate,
physicalstores.CLOSED_DATE as physicalstore_closedate)
from physicalstores , brandedstores ,companies
where physicalstores.physicalstores_id = brandedStores.PHYSICALSTORES_ID and
physicalstores.COMPANIES_ID = companies.COMPANIES_ID and
brandedstores.closed_date is not null
oracle gives a ora _917 fault about a missing comma , but I can not se what is wrong.
I will be glad, if you can give me an example with a right syntax where a subtype is selected from other/s tables an inserted in table of its supertype.
kinds regards
steen ostersenHi
I see two problems with your statement:
1) The utilization of the values clause is not permitted along with a subquery.
2) The AS are not allowed.
So, something like that should work:
insert into Action_Logs
select CloseStore_Logs_t(null,
physicalstores.physicalstores_id,
brandedstores.BRANDEDSTORES_ID,
physicalstores.COMPANIES_ID,
brandedstores.CREATED_BY,
brandedstores.CREATED_DATE,
brandedstores.DELETED,
brandedstores.CLOSED_DATE,
physicalstores.CLOSED_DATE)
from physicalstores , brandedstores ,companies
where physicalstores.physicalstores_id = brandedStores.PHYSICALSTORES_ID and
physicalstores.COMPANIES_ID = companies.COMPANIES_ID and
brandedstores.closed_date is not null
HTH
Chris -
Copying data from one table to another, but not duplicate
Good afternoon!
I am new to Oracle SQL, I have a difficulty.
I have a script that copies or add another table with data from another table.
If the table already has 01 "Registry 01" when you make a copy of the data in table 02, can not duplicate the "Registry 01" again.
As the table already exists since the beginning of the year before last and duplicate information, I can not apply the UNIQUE constraint because of the error. I have to make this change from now.
How to perform this validation so that no duplicate data?
DECLARE
w_cont NUMBER;
CURSOR c_simpro IS
SELECT sc.cd_simpro,
sc.ds_produto,
sp.qt_embalagem,
MAX(sp.dt_vigencia)
FROM simpro_cadastro sc,
simpro_preco sp
WHERE sc.cd_simpro = sp.cd_simpro
GROUP BY sc.cd_simpro,
sc.ds_produto,
sp.qt_embalagem;
BEGIN
FOR r_simpro IN c_simpro LOOP
w_cont := 0;
SELECT COUNT(1)
INTO w_cont
FROM pls_material pm
WHERE pm.cd_material_ops = r_simpro.cd_simpro;
IF w_cont = 0 THEN
INSERT INTO pls_material(nr_sequencia,
dt_atualizacao,
nm_usuario,
dt_atualizacao_nrec,
nm_usuario_nrec,
ie_tipo_despesa,
cd_estabelecimento,
nr_seq_estrut_mat,
cd_simpro,
ds_material,
ie_situacao,
ds_material_sem_acento,
dt_inclusao,
cd_material_ops_orig,
cd_unidade_medida,
cd_material_ops,
qt_conversao_simpro)
VALUES(pls_material_seq.nextval,
SYSDATE,
'ES-SIMPRO',
SYSDATE,
'ES-SIMPRO',
3,
1,
3,
r_simpro.cd_simpro,
r_simpro.ds_PRODUTO,
'A',
r_simpro.ds_PRODUTO,
SYSDATE,
r_simpro.cd_simpro,
'un',
TRIM(to_char(r_simpro.cd_simpro,'0000099999')),
r_simpro.qt_embalagem);
COMMIT;
END IF;
IF w_cont > 0 THEN
UPDATE pls_material p
SET p.qt_conversao_simpro = r_simpro.qt_embalagem,
p.dt_atualizacao = SYSDATE
WHERE p.cd_simpro = r_simpro.cd_simpro;
COMMIT;
END IF;
END LOOP;
END;
Edited by: 983464 on 22/01/2013 10:30Hi,
in addition to what Marwin has already said, I suggest you to post CREATE TABLE and INSERT statements (as mentioned in the FAQ).
The error you are getting from MERGE command is because you need a way to uniquely identify within the table. So it's is important to know also if your table has a primary key/unique index so the keys could to be used in the MERGE command.
Additionally when you put some code or output please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
Regards.
Al
Maybe you are looking for
-
Time machine multiple internal hard drives to multiple external hard drives
I have four internal hard drives that I back up to four separate dedicated external hard drives. I have upgraded to leopard and would like to use TIME MACHINE but I don't see how I can set up this unique back up system. Up until now I have been using
-
Rename the opening file & then open it
Hi, I am looking for a script which can - 1. On opening a file rename it. For e.g. Rename "FileName1.indd" to "FileName1-in-use.indd" 2. Then open the file "FileName1-in-use.indd" 3. Then on closing rename it back to "Filename1.indd" Is it possible?
-
WD Message Manager - collect messages
Hi All, we work with 2 WD-applications reporting their message in the messagearea of WD-application#1 How can I report messages without losing existing messages? I found note 940762 in this forum saying that it is possible to collect message using th
-
I have a Nokia 6230i and wish to set speed dials as I had on my previous phone, a Nokia 8210. On the 8210 I could set the speed dial on all numbers 1 - 9, including the No. 1 button. By pressing the key pad No. (e.g. number 1 button) and then pressin
-
Ok, so I may not be the sharpest tool in the shed....
....and this is my first "pad" type device....but this thing is causing me a freakin' migrane.... Why can this thing go thru it's initial setup without a wireless connection....??? Did somebody seriously believe that that was a good idea...??? Of cou