Update rows with a column
hi
gurus
updating a row with a column
i have first table with 5 columns
id telephone, telex, mobile,email,santige
1 9123455 12 987 @ 12452
i have another second table having a columns like
id comm , commid
1 3245 1
1 23 2
1 786 3
1 we@ 4
1 122 5
the commid is
1-telephone 2-telex,3-mobile,4-email,5--santige
the problem is i want to update the second table with the data of first table
final data will comes like this
id comm , commid
1 9123455 1
1 12 2
1 987 3
1 @ 4
1 12452 5
please adjust the data below the columns (for view)
Something like
UPDATE table2 t2
SET comm = (SELECT DECODE(t2.commid, 1, telephone,
2, telex,
3, mobile,
4, email,
5, santige)
FROM table1 t1
WHERE t1.id = t2.id)should work.
CREATE TABLE table1 (
id NUMBER,
telephone VARCHAR2(100),
telex VARCHAR2(100),
mobile VARCHAR2(100),
email VARCHAR2(100),
santige VARCHAR2(100)
CREATE TABLE table2 (
id NUMBER,
comm VARCHAR2(100),
commid NUMBER
INSERT INTO table1 VALUES( 1, 'telephone', 'telex', 'mobile', 'email', 'santige' );
BEGIN
INSERT INTO table2 VALUES( 1, 'x', 1 );
INSERT INTO table2 VALUES( 1, 'x', 2 );
INSERT INTO table2 VALUES( 1, 'x', 3 );
INSERT INTO table2 VALUES( 1, 'x', 4 );
INSERT INTO table2 VALUES( 1, 'x', 5 );
END;
UPDATE table2 t2
SET comm = (SELECT DECODE(t2.commid, 1, telephone,
2, telex,
3, mobile,
4, email,
5, santige)
FROM table1 t1
WHERE t1.id = t2.id);
SQL> SELECT * FROM table2;
ID COMM COMMID
1 telephone 1
1 telex 2
1 mobile 3
1 email 4
1 santige 5Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC
Similar Messages
-
Update Rows with info from other Rows in Same Table.
I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". So what am I doing wrong here??? How can I update only the rows that where also in last months run???
Thanks in advance for any help!
Update OpenIssues OI1
Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
(Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
From OpenIssues OI2
Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
SQLMeHi,
Welcome to the forum!
SQLMe wrote:
I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". If the aliases c1 and c2 aren't defined anywhere, then you can't use them anywhere.
The WHERE clause of the UPDATE statement can only reference the table being updated, ot1 in this case.
So what am I doing wrong here??? How can I update only the rows that where also in last months run???
Thanks in advance for any help!
Update OpenIssues OI1
Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
(Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
From OpenIssues OI2
Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
------------There's a syntax error in the last line. Either something got lost when you posted the code, or you just don't want the keyword AND. You certainly don't want AND immediately after WHERE.
In general, if it's not obvious how to do an UPDATE, then UPDATE is the wrong tool: you want MERGE instead.
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
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.
See the forum FAQ {message:id=9360002} -
Applying table scroll bar for only table rows with table columns fixed.
hi oa gurus,
i had implemented table scroll bars using oarawtextbean , there is no problem in vertical and horizontal scroll bar working its working fine. but the requirement is i need to scroll only the table rows with table columns fixed. so , how to achieve the table scroll for only table datas neglecting table headers.
the code for vertical and horizontal bars scroll is like this,
OARawTextBean ors = (OARawTextBean)webBean.findChildRecursive("raw1");
ors.setText(div id=tabledivid style=height:500px;width:100%; overflow:auto>);
OARawTextBean ore = (OARawTextBean)webBean.findChildRecursive("raw2");
ore.setText("</div>");
where raw1 and raw2 are rawtextbean created above and below of the table . but i dont know hoow to apply this only for table rows neglecting table columns , can anybody give any ideas.
pelase this is very urgent , can u help me in this regards
thanks
Edited by: user630121 on Sep 29, 2008 5:17 AM
Edited by: user630121 on Sep 29, 2008 5:18 AMhi,
I have a similar task to do... Only to apply scrollbar at the table level.
I tried using the above mentioned but I am facing Null Pointer Exception..
Please explain about raw1 and raw2
Rahul -
I have 105 rows with alternating columns of No. sold
I have 105 rows with alternating columns of No. Sold and Amount Sold, for six different dates. I want the two totals columns on the right to sum every other column for the Total No. Sold and the same but one over for Total Amount Sold. I know how to do this for a single row, as I have done for the last totals row. How could I do the formula for all rows without entering it for each one, or if that is not possible, maybe I could copy the formula in some way to make it easier?
rogerfrombellingham wrote:
... I know how to do this for a single row, as I have done for the last totals row. How could I do the formula for all rows without entering it for each one, or if that is not possible, maybe I could copy the formula in some way to make it easier?
Yes, Roger, you can easily copy those formulas for all the rest of the 105 rows.
Select the two totals cells, click on the little circle in the lower right corner of the selection and drag it to the bottom.
Jerry -
Update rows with a sequence which fall under same group.
Hi Friends,
I have sample table with following data :
ID DIV NEW_ID
1 A
2 A
3 B
4 B I want to update the column NEW_ID with a sequence value for the rows with same DIV value.
My result should look like below :
ID DIV NEW_ID
1 A 1001
2 A 1001
3 B 1002
4 B 1002How can I accomplish with a single update ?
Thanks
Raj.This isn't pretty, but it should work ....
ME_XE?create table table1 (col1 number, col2 varchar2(1), col3 number);
Table created.
Elapsed: 00:00:00.04
ME_XE?insert into table1 values (1, 'A', NULL);
1 row created.
Elapsed: 00:00:00.06
ME_XE?insert into table1 values (2, 'A', NULL);
1 row created.
Elapsed: 00:00:00.01
ME_XE?insert into table1 values (3, 'B', NULL);
1 row created.
Elapsed: 00:00:00.00
ME_XE?insert into table1 values (4, 'B', NULL);
1 row created.
Elapsed: 00:00:00.00
ME_XE?
ME_XE?
ME_XE?create sequence s start with 1001 increment by 1;
Sequence created.
Elapsed: 00:00:00.00
ME_XE?create or replace function get_s_nextval
2 return number
3 as
4 o_val number;
5 begin
6 select s.nextval into o_val from dual;
7 return o_val;
8 end;
9 /
Function created.
Elapsed: 00:00:00.54
ME_XE?
ME_XE?
ME_XE?merge into table1 t using
2 (
3 with data
4 as
5 (
6 select --+ MATERIALIZE
7 col2, get_s_nextval as next_value
8 from
9 (
10 select distinct col2
11 from table1
12 where col3 is null
13 )
14 )
15 select * from data
16 ) s
17 on (s.col2 = t.col2)
18 when matched then update set t.col3 = s.next_value;
4 rows merged.
Elapsed: 00:00:00.20
ME_XE?
ME_XE?
ME_XE?select * from table1;
COL1 COL COL3
1 A 1001
2 A 1001
3 B 1002
4 B 1002
4 rows selected.
Elapsed: 00:00:00.03
ME_XE? -
Update row with more data - JTable with Abstracttablemodel
Hello!
I got some problems with my program, im using jtable with abstracttablemodel.
First I include content into the jtable by pressing ”New Content”, then it will pop up a dialog which I fill with information as you can see in the picture.
http://img42.imageshack.us/img42/6969/jtable.jpg
But when its done, I want to borrow it and update that row with more information as you can see if its loaned, if it is their shall be a checkbox, name and phone there. I don’t really know how to do this. Suppose I should do a similar metodh as when I’m adding and removing content. The question is how do I do that? I’ve been looking at some tips and hints on google. It seems to me that should use “fireTableRowsUpdated” but not really sure if its right and how to. When I’m borrowing the specific row I guess I need to check which row is clicked before borrowing and then fill in the information and update the table.The borrow button will also pop up a dialog with 3 fields to fill. Here is the code I wrote for adding and removing. I’ve tried with the update but its not right which I’m going to use when borrowing objects from the database. Please help!
Code from the abstracttablemodel
private ArrayList<Objects> obj = new ArrayList<Objects>();
public void add(Objects o) {
obj.add(o);
fireTableRowsInserted(obj.size()-1, obj.size()-1);
public void remove(int o) {
int index = obj.indexOf(o);
obj.remove(o);
fireTableRowsDeleted(index, index);
public void update (Objects o){
// Not sure how to do here
//int index = obj.indexOf(o);
//fireTableRowsUpdated(index,index);
}Code for the button in the main program.
if (arg.getSource() == borrow) {
// How should I do here? I need to implement the BorrowDialog, check if a row is pressed then update? How do I do that?
BorrowDialog newLoan = new BorrowDialog(frame);
if(table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before loan");
else
dir.update(newLoan.getLoan());
table.repaint();
}Code for BorrowDialog
public class BorrowDialog extends JDialog implements ActionListener {
//implements JTextFields, Buttons,Labels and Panels.
public BorrowDialog(JFrame parent) {
//Setting buttons to panels and such
public Objects getLoan(){
return loan;
public void setLoan()
// Not sure if this is right, as I leave some fields empty, will it be empty when its updating aswell?
// I tried with add data then it just will be a new row, when I will update a specific row
loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
public void actionPerformed(ActionEvent arg) {
if (arg.getActionCommand().equals("Save")) {
System.out.println("save");
setLoan();
dispose();
}All help is appreciated!
Edited by: iTech34 on Feb 22, 2010 3:27 AM
Edited by: iTech34 on Feb 22, 2010 3:31 AM
Edited by: iTech34 on Feb 22, 2010 3:58 AMLook up for the rest of the code!
I explained everything on the first post, so please read there so you know the problem I got.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Database implements ActionListener {
private final int WIDTH = 800;
private final int HEIGHT = 800;
private JTable table = new JTable();
private JFrame frame = new JFrame("Database");
private JButton addContent = new JButton("New content");
private JButton borrow = new JButton("Borrow");
private JButton returnObject = new JButton("Return");
private JButton remove = new JButton("Remove");
private JButton save = new JButton("Save");
private JButton load = new JButton("Load");
private JButton exit = new JButton("Exit");
private Directory dir = new Directory();
private JPanel buttonPanel = new JPanel();
private JPanel mainPanel = new JPanel();
public Database() {
// BUTTONS
buttonPanel.add(addContent);
buttonPanel.add(remove);
buttonPanel.add(borrow);
buttonPanel.add(returnObject);
buttonPanel.add(save);
buttonPanel.add(load);
buttonPanel.add(exit);
// ACTION LISTENERS
addContent.addActionListener(this);
remove.addActionListener(this);
borrow.addActionListener(this);
returnObject.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
exit.addActionListener(this);
// JTABLE
table = new JTable(dir);
table.setAutoCreateRowSorter(true);
table.setRowHeight(25);
JScrollPane JScroll = new JScrollPane(table);
// PANELS
mainPanel.setLayout(new BorderLayout());
mainPanel.add("North", buttonPanel);
mainPanel.add("Center", JScroll);
// FRAME
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public void actionPerformed(ActionEvent arg) {
if (arg.getSource() == addContent) {
Dialog newDialog = new Dialog(frame);
dir.add(newDialog.getItem());
if (arg.getSource() == remove) {
if (table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before remove");
else
dir.remove(table.getSelectedRow());
if (arg.getSource() == borrow) {
// Not sure how to do here! I need to check which row I've clicked and take that row into BorrowDialog as argument i suppose.. please explain
BorrowDialog newLoan = new BorrowDialog(frame);
if(table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before loan");
else
dir.update(newLoan.getLoan());
table.repaint();
if (arg.getSource() == returnObject) {
if (arg.getSource() == save) {
dir.writeFile();
if (arg.getSource() == load) {
Objects[] tempObject = dir.readFile("info.txt");
for (int i = 0; tempObject[i] != null; i++)
dir.add(tempObject);
if (arg.getSource() == exit){
frame.dispose();
public static void main(String[] argv) {
new Database();
}import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class BorrowDialog extends JDialog implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 400;
private JButton exitDialog = new JButton("Exit");
private JButton saveDialog = new JButton("Save");
private JTextField loanField = new JTextField();
private JTextField nameField = new JTextField();
private JTextField phoneField = new JTextField();
private JLabel loanLabel = new JLabel("Loan");
private JLabel nameLabel = new JLabel("Name");
private JLabel phoneLabel = new JLabel("Phone");
private JPanel eastPanel = new JPanel();
private JPanel southPanel = new JPanel();
private JPanel westPanel = new JPanel();
private GridLayout layout = new GridLayout(3, 1);
private Objects loan;
public BorrowDialog(JFrame parent) {
super(parent, "Borrow", true);
southPanel.add(saveDialog);
southPanel.add(exitDialog);
westPanel.add(loanLabel);
eastPanel.add(loanField);
westPanel.add(nameLabel);
eastPanel.add(nameField);
westPanel.add(phoneLabel);
eastPanel.add(phoneField);
westPanel.setLayout(layout);
eastPanel.setLayout(layout);
add("West", westPanel);
add("Center", eastPanel);
add("South", southPanel);
saveDialog.addActionListener(this);
exitDialog.addActionListener(this);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setSize(WIDTH, HEIGHT);
getContentPane();
setVisible(true);
public Objects getLoan(){
return loan;
public void setLoan()
// Can I really do like this? Will the the specific row I've chosen be overwriten entirly with blank elements in the six columns as I left empty(see below, when I send the arguments into the constructor)?
loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
public void actionPerformed(ActionEvent arg) {
if (arg.getActionCommand().equals("Save")) {
System.out.println("save");
setLoan();
dispose();
if (arg.getSource() == exitDialog) {
dispose();
Edited by: iTech34 on Feb 22, 2010 11:19 AM
Edited by: iTech34 on Feb 22, 2010 11:20 AM -
Combining Multiple Rows into single row with multple columns
Hi Experts,
I have the following requirement, kindly help me.
I have data in my table like below.
ID NAME DEPT
1 Sam 10
1 Sam 20
2 alex 30
2 alex 40
2 alex 50
3 vinod 60
3 vinod 70
I want to show the same data into single row with dynamically generating columns for DEPT. I want show like below.
ID NAME DEPT1 DEPT2 DEPT3
1 Sam 10 20
2 alex 30 40 50
3 vinod 60 70
It's urgent requirement, kindly help me.
Thanks in advance.Right I've had my drink, so what was this "urgent" question then?
798616 wrote:
I have data in my table like below.
ID NAME DEPT
1 Sam 10
1 Sam 20
2 alex 30
2 alex 40
2 alex 50
3 vinod 60
3 vinod 70
I want to show the same data into single row with dynamically generating columns for DEPT. I want show like below.Dynamic numbers of columns eh! Tricky.
If you understand how SQL statements are executed it's along these lines...
1. Open Cursor
2. Parse SQL statement and determine columns
3. Bind in any input values
4. Fetch data
5. Bind out values to columns
6. Repeat step 3 until no more data
7. Close cursor
Now, you're expecting that you can determine the columns (step 2) from the fetched data (step 4 onwards). You can't. The SQL engine needs to know the expected columns before any data is fetched so, it can't base the number of columns on the data itself.
If you need that requirement, you would need to query the data first and build up a dynamic query based on the data and then execute that dynamically built query to fetch the data and pivot it into those columns, which means that you have queried the data twice. Not good practice and not good (or simple) coding.
What you're talking of doing is something that should be handled at the presentation/interface layer, not as part of the data fetch.
Typically these sorts of things are handled most easily in report generation/writer tools such as Oracle Reports, Business Objects etc. where they fetch the data from the database and then process it to format it on the display, pivoting the results as required.
It's not something that lends itself to be easily achieved in SQL. Yes, SQL can do pivoting of data quite easily, but NOT with a dynamic number of columns.
If you were to specify that there is a maximum number of columns that you could get (rather than wanting it dynamic), then you can do it simply in SQL with the max-decode method...
SQL> ed
Wrote file afiedt.buf
1 with t as (select deptno, ename, row_number() over (partition by deptno order by ename) as rn from emp)
2 --
3 select deptno
4 ,max(decode(rn,1,ename)) as ename1
5 ,max(decode(rn,2,ename)) as ename2
6 ,max(decode(rn,3,ename)) as ename3
7 ,max(decode(rn,4,ename)) as ename4
8 ,max(decode(rn,5,ename)) as ename5
9 ,max(decode(rn,6,ename)) as ename6
10 ,max(decode(rn,7,ename)) as ename7
11 ,max(decode(rn,8,ename)) as ename8
12 ,max(decode(rn,9,ename)) as ename9
13 ,max(decode(rn,10,ename)) as ename10
14 from t
15 group by deptno
16* order by deptno
SQL> /
DEPTNO ENAME1 ENAME2 ENAME3 ENAME4 ENAME5 ENAME6 ENAME7 ENAME8 ENAME9 ENAME10
10 CLARK KING MILLER
20 ADAMS FORD JONES SCOTT SMITH
30 ALLEN BLAKE JAMES MARTIN TURNER WARD
SQL> -
Updating row with a blob value
Hi, I get the following error when trying to update a row with a Blob value. I am using a Bfile as the external file ref. to put into the Blob.
ORA-22920: row containing the LOB value is not locked
The code that I'm using is the following:
PROCEDURE IOSYS_PCT.insert_blob AS
length NUMBER;
image BLOB;
image_file BFILE;
bf_dir VARCHAR2(40);
bf_name VARCHAR2(40);
BEGIN
SELECT temp_blob INTO image FROM temp_blob; /*initialise image with empty_blob()*/
SELECT image_sm, image_sm_file INTO image, image_file FROM images WHERE
file_id=1;
dbms_lob.filegetname(image_file,bf_dir,bf_name);
DBMS_LOB.FILEOPEN(image_file,DBMS_LOB.FILE_READONLY);
LOCK TABLE images IN ROW EXCLUSIVE MODE;
length := DBMS_LOB.GETLENGTH(image_file);
DBMS_LOB.LOADFROMFILE(image,image_file,DBMS_LOB.GETLENGTH(image_file));
DBMS_LOB.FILECLOSE(image_file);
UPDATE images SET image_sm = image WHERE file_id=1;
END;
Please help as I have ran out of ideas what could be wrong.
Thanx Andre
nullHi, I get the following error when trying to update a row with a Blob value. I am using a Bfile as the external file ref. to put into the Blob.
ORA-22920: row containing the LOB value is not locked
The code that I'm using is the following:
PROCEDURE IOSYS_PCT.insert_blob AS
length NUMBER;
image BLOB;
image_file BFILE;
bf_dir VARCHAR2(40);
bf_name VARCHAR2(40);
BEGIN
SELECT temp_blob INTO image FROM temp_blob; /*initialise image with empty_blob()*/
SELECT image_sm, image_sm_file INTO image, image_file FROM images WHERE
file_id=1;
dbms_lob.filegetname(image_file,bf_dir,bf_name);
DBMS_LOB.FILEOPEN(image_file,DBMS_LOB.FILE_READONLY);
LOCK TABLE images IN ROW EXCLUSIVE MODE;
length := DBMS_LOB.GETLENGTH(image_file);
DBMS_LOB.LOADFROMFILE(image,image_file,DBMS_LOB.GETLENGTH(image_file));
DBMS_LOB.FILECLOSE(image_file);
UPDATE images SET image_sm = image WHERE file_id=1;
END;
Please help as I have ran out of ideas what could be wrong.
Thanx Andre
null -
How to select rows with Empty Column Entry
I am trying to select all rows with an empty column
select row1 from table where row2=' ';
Any suggestions. I tried a space and no space in between the ''.An (theoretical) argument could be made that an empty string is not NULL (uknown), however Oracle's SQL and PL/SQL engines make no such distinction for VARCHAR2 and CHAR data types. As stated, you must use NULL as the comparison.
Michael -
Unable to update row on parition column
Hi,
I am facing problem while updating rows in a table which is having partition and the update is on the partition key.
Kindly any benefitial will be helpful for me.
Thanks and RegardsHi,
When I am operating the process through sql plus the error is not showing.
But in Toad while updating Error showing:
Row may have been deleted by another user or a trigger or ROWID may have changed due to update.
Thanks and Regards -
Master-detail: one detail row with multiple columns
Hi All,
I have a normal master-detail situation in the databse, in the form however all detail rows should be displayed in one single row, using more columns. The number of details are limited, so I can use a predefined number of text-items.
Any ideas on how to implement this?
Regards,
Michielcreate a function that returns your details. e.g. :
function get_detail (P_PK, P_rownum) ...
let's use the example dept and emp. Your master is dept. Your detail is emp. deptno is the PK for the master table.
you have in your form multi-records of dept and maybe 5 items for employees. The name of the text-items TI_data_1 .. TI_data_5. In the post-query-trigger you code :
:DEPT.TI_data_1 := get_detail (:DEPT.DEPTNO, 1);
:DEPT.TI_data_2 := get_detail (:DEPT.DEPTNO, 2);
if you need more columns create a loop and use the built-in COPY for assigning the detail-values to the text-items.
the get_detail e.g. is a select-statement:
SELECT ENAME
FROM EMP
WHERE DEPTNO = P_PK
AND rownum = P_rownum
ORDER BY EMPNO
try it
Gerd -
Convert multiple rows to one row with multiple columns
Hi
i have a table Match_1 with 2 columns 'Source' and 'target'.One source can have multiple targets and that number could be anything
CREATE TABLE Match_1
Source CHAR(1),
Target CHAR(1)
INSERT INTO Match_1 VALUES ('A', 'B');
INSERT INTO Match_1 VALUES ('A', 'C');
INSERT INTO Match_1 VALUES ('A', 'D');
INSERT INTO Match_1 VALUES ('A', 'E');
INSERT INTO Match_1 VALUES ('V', 'X');
INSERT INTO Match_1 VALUES ('V', 'Y');
INSERT INTO Match_1 VALUES ('V', 'X');
INSERT INTO Match_1 VALUES ('V', 'W');
COMMIT;
i need to get my output in the below format
Source target 1 target 2 target 3 target 4 target n
A B C D
V X Y Z W
Could you please provide me the required SQL.
REgards
-LearnsequelWhat is your database version (4 digit) ? also my example won't be generate columns for your information:
it will produce a result like that :
select source, listagg(target,',') within group (order by target)
from match_1
group by source;
A B,C,D,E
V W,X,X,Yps: in previos post, I wrote "with" word wrong in sql. -
Returning two rows with one column containing only one place
Dear all;
I have a query that returns two rows similar to this below
ID PLACE PROGRAM
A NEWYORK PROGRAM A
A NEWYORK PROGRAM B
I would like this instead
ID PLACE PROGRAM
A NEWYORK PROGRAM A
PROGRAM B
All help is appreciated. Thank you.Edited by: user13328581 on Mar 22, 2011 11:52 AMuser13328581 wrote:
WOW...THanks a lot Solomon, I have never used partitions and row_number in such a manner...can you please explain your logic.Sure:
row_number() over(partition by id order by place,program)This will take all rows returned by the query andsplit them into buckets (partitions) by id. Inside each bucket it will order rows by place and program and assign them row numbers. So for each ID row number 1 will be row with first (alphabetically) place first programt. And this is the row where we want ID to show up. That is why we wrap the above analytic function in CASE statement which will do exactly that. Now:
row_number() over(partition by id,place order by program)does pretty much the same just bucket is ID and PLACE combination. So for each such combination we want to show only for the first (alphabetically) programt.
Now notice in ORDER BY clause I prefix ID and PLACE with table alias. You must do it since otherwise query alias ID and PLACE will take precedence resulting in wrong sort order (remember we nulled all ID and PLACE except for row number 1).
SY. -
How to select rows with duplicate column values
hi,
i have a table property_details which has these 2 columns customerno and propertyno a customer can have many properties and property number has to be unique. but somehow these property number has been duplicated at an earlier stage so i have for a customer with many properties the same property number
how i will select such records whose asset numbers are the same
for ex
customer no property no
a1300 1
a1300 1
a1300 1
a2330 10
a2330 10
a2330 10
kindly suggest me a solutionthis example might be of help.
SQL> select * from employees;
YEAR EM NAME PO
2001 02 Scott 91
2001 02 Scott 01
2001 02 Scott 07
2001 03 Tom 81
2001 03 Tom 84
2001 03 Tom 87
6 rows selected.
SQL> select year, empcode, name, position,
2 row_number() over (partition by year, empcode, name
3 order by year, empcode, name, position) as rn
4 from employees;
YEAR EM NAME PO RN
2001 02 Scott 01 1
2001 02 Scott 07 2
2001 02 Scott 91 3
2001 03 Tom 81 1
2001 03 Tom 84 2
2001 03 Tom 87 3
6 rows selected.
SQL> Select year, empcode, name, position
2 From (Select year, empcode, name, position,
3 row_number() over (partition by year, empcode, name
4 order by year, empcode, name, position) as rn
5 From employees) emp
6 Where rn = 1;
YEAR EM NAME PO
2001 02 Scott 01
2001 03 Tom 81
SQL> -
Combine update stmts with different columns and criteria
Hi All,
I have the following 3 update stmts that update the same table. The table DSVEHS has 45 million rows. The table PPDSDETL has 95 million rows. How to combine them? I'd like to reduce the times to scan those tables. There is a primary key on PPDSDETL for dipoln, direnn, diseqn, didscd and another column not in the query.
Please give me some suggestions. Thank you in advance.
UPDATE DSVEHS
SET accfgn_sur = 'Y'
WHERE EXISTS (SELECT 'X' FROM PPDSDETL
WHERE polnum = dipoln
AND polren = direnn
AND polseq = diseqn
AND UPPER (TRIM (didscd)) = 'ACCFGN');
update DSVEHS
set mviofg_sur = 'Y'
where exists (select 'X' from PPDSDETL
where POLNUM=DIPOLN
and POLREN =DIRENN
and POLSEQ =DISEQN
and upper(trim(DIDSCD)) ='MVIOFG' ) ;
update DSVEHS
set accfre_dsc= 'Y'
where exists (select 'X' from PPDSDETL
where POLNUM=DIPOLN
and POLREN =DIRENN
and POLSEQ =DISEQN
and upper(trim(DIDSCD)) ='ACCFRE' ) ;Hi,
user13081819 wrote:
Hi Frank:
Here is a set of sample result:
POLNUM POLREN POLSEQ VEHNUM DRVNUM TRANSD MULTIC PRODUC HOMEOW NONOWN RENEWA DRIVER OT ACCFGN_SUR MVIOFG_SUR ACCFRE_DSC
1111111 0 1 2 0 mmmmmm xxxxxx Y N Y
2222222 0 3 1 0 Y N Y
...This site normally won't print multiple spaces in a row.
Whenever you post formatted text, like your results, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
The table structures are:
DSVEHS
Name Null? Type
POLNUM NOT NULL NUMBER(9)
POLREN NOT NULL NUMBER(2)
POLSEQ NOT NULL NUMBER(2)
...Post CREATE TABLE statements instead.
Please let me know if you need more information.Besides the things mentioned above, post INSERT statements for the sample data that produces the given results.
Did you say which version of Oracle you're using?
Maybe you are looking for
-
Problem reinstalling J2EE 1.4 on Windows XP
Hi everyone, I installed once the j2ee 1.4 package without any problems, but I had to uninstall it. Now during the last 3 days I've been trying to reinstall it, but everytime I try I got the same error during the installation process: ERROR - default
-
How to Track Reservation Changes...?
Freinds, Can any one tell me how to track the Reservation(MB23) changes.????? I want to know when the Reservation has been created and when was the last change done for that Reservation?? I tried to find in table RESB but no luck... Chandra.
-
Problem Installing Apps Windows 8 Store
I have tried to update certain apps I have and also install new ones and it gives me error code 0x80240437, I havent had problems installing apps up until now I dont know what to do?
-
Equium M40X and a wireless network
Hey all, I've just got my new Equium Notebook and when i try to connect to my wireless home network, i can only manage to connect with limited or no connectivity (it can't refresh the ip address either). I'm positive its nothing to do with the networ
-
After click restore button the restore started but it only go up to 75% then it got drop. This is for iPad2. Please advise. Thanks.