Update a column in each row in my table that have similar values in another column
Hi All,
I have a table in my DB.
This table has values like this:
Name
Key
a
1
a
2
a
3
a
2
b
4
b
5
b
5
I need to change the name to a different name for keys that are different. For same keys, the name must be same.
Here I need to rename the 'a' to different name, but make sure that the 'a' that have 2 as the key have same name .
Similarly, i've to rename the 'b' to different name , but make sure that the 'b' that have 5 as the key have the same name.
How can I achieve this in sql? I dont know how to use cursor and complex queries, as i'm new to SQL.
Please help
Thanks,
Vid
Vidya Suryanarayana
Ok. The output should be like this:
Note here, that the names with same keys have same names.
name
key
a1
1
a2
2
a3
3
a2
2
b1
4
b2
5
b2
5
Thanks,
Vid
Vidya Suryanarayana
Similar Messages
-
Create a new column in a table that compares the value of one column with its previous value
The DDL:
DECLARE
@T TABLE
IDNO
int,
name
varchar(40),
[Date]
datetime2,
Price1
float,
Price2
float
DECLARE
@K TABLE
IDNO
int,
name
varchar(40),
[Date]
datetime2,
Price1
float,
Price2
float
INSERT
INTO @T
VALUES(22,'C_V_Harris','2014-01-02 10:23:49.0000000',
23.335,
23.347)
INSERT
INTO @T
VALUES(21,'C_V_Harris','2014-01-02 10:05:13.0000000',
23.357,
23.369)
INSERT
INTO @T
VALUES(20,'C_V_Harris','2014-01-02 09:56:15.0000000',
23.364,
23.377)
INSERT
INTO @T
VALUES(19,'C_V_Harris','2014-01-02 09:45:26.0000000',
23.351,
23.367)
INSERT
INTO @T
VALUES(18,'C_V_Harris','2014-01-02 09:43:20.0000000',
23.380,
23.396)
INSERT
INTO @T
VALUES(17,'C_V_Harris','2014-01-02 09:34:28.0000000',
23.455,
23.468)
INSERT
INTO @T
VALUES(16,'C_V_Harris','2014-01-02 09:30:37.0000000',
23.474,
23.486)
INSERT
INTO @T
VALUES(15,'C_V_Harris','2014-01-02 09:18:12.0000000',
23.419,
23.431)
INSERT
INTO @T
VALUES(14,'C_V_Harris','2014-01-02 09:16:06.0000000',
23.360,
23.374)
INSERT
INTO @K
SELECT
ROW_NUMBER()
OVER (ORDER
by IDNO)
AS RN,*
FROM
@T
SELECT
* FROM
@K
--not working:
SELECT
a.RN,a.Price2
FROM
@K a
INNER
JOIN @K
b
ON
a.RN=b.RN-1
WHERE
a.Price2>b.Price2
I need to create a view with a column (say 'Comp' below) that compares the value of each row in Price2 with the previous Price2 row, and it is greater then +1, the
same 0, and less -1.
The processed table should be:
IDNO
name
Date
Price1
Price2
Comp
22
C_V_Harris
1/2/2014 10:23:49
23.335
23.347
0
21
C_V_Harris
1/2/2014 10:05:13
23.357
23.369
1
20
C_V_Harris
1/2/2014 9:56:15
23.364
23.377
1
19
C_V_Harris
1/2/2014 9:45:26
23.351
23.367
-1
18
C_V_Harris
1/2/2014 9:43:20
23.38
23.396
1
17
C_V_Harris
1/2/2014 9:34:28
23.455
23.468
1
16
C_V_Harris
1/2/2014 9:30:37
23.474
23.486
1
15
C_V_Harris
1/2/2014 9:18:12
23.419
23.431
-1
14
C_V_Harris
1/2/2014 9:16:06
23.36
23.374
-1
How can I structure the statement to get (the most recent - order by date ) result for Comp?Satheesh Variath, I just had to make some corrections from your script to get the correct answer:
CREATE
VIEW vw_Comp
AS
SELECT
TOP 1 t.IDNO,t.name,t.[Date],t.Price1,t.Price2,
CASE
WHEN t.Price2
> LAG(Price2,1)
OVER (PARTITION
BY name
ORDER BY IDNO)
THEN 1
WHEN t.Price2
< LAG(Price2,1)
OVER (PARTITION
BY name
ORDER BY IDNo)
THEN -1
ELSE 0
END
AS Comp
FROM
@T t
ORDER
BY DATE
DESC
The adjustments: the selection of the most recent comparison (Top 1) and the use of the function LAG (instead of LEAD) to get the previous value of the column. -
How can can i subtract the value of the column in each row ?
I want to subtract the value of the column in each row if the row is not enough then continue to next row.
For example
ID QTY
A 20
B 40
C 60
I want to update this table by subtract the value of the column (QTY) out 70 so the result i want will be
ID QTY
A 20 - 70 = -50 --> 0 this row will be updated to 0 and 50 will continue to next row
B 40 - 50 = -10 --> 0 this row will be updated to 0 and 10 will continue to next row
C 60 - 10 = 50 --> Stop loop
How can i write the sql query for this operation , ThanksPlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea,
do you? Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. What did you try on your own before posting? I will bet that you did nothing! You expect other people to do your job or homework for you.
>> I want to subtract the value of the column in each row if the row is not enough then continue to next row. <<
This makes no sense. Rows have no ordering; that is a spreadsheet. There is no such thing as a generic “id” in RDBMS. And an identifier is not a sequence which would have an ordering.
CREATE TABLE Foobar
(something_seq INTEGER NOT NULL PRIMARY KEY,
onhand_qty INTEGER NOT NULL);
Learn how to use the SUM()OVER() and LAG() aggregate functions, post what you tried for yourself and then we will help you.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Upload a file where no. of columns for each row is not fixed...
Hi All,,
I have to upload a file......
number of columns for each rows are not fixed ....
e.g.
Posting Date Company Code Currency Header Text Cost Center Internal Order Ref 1 Ref 2 Line Text Account no. Amount Account no. Amount Account no. Amount Account no. Amount Account no. Amount Account no. Amount Account no. Amount
31-05-09 1000 EUR PAYROLL 05/2009 1234 123456 123456 seaman RU 999999 9,999.99
31-08-09 1000 EUR PAYROLL 05/2009 678 98765 98765 officer GB 600015 4,560.00 600035 2,125.50 600020 1,325.40 600025 245.75 600030 300.00 280010 1,000.00 281091 6,000.00
its in tab delimited txt file.....
how to upload this type of file..
Plz suggest....
thnx
rahulHi,
Define your internal table like this.
TYPES: BEGIN OF upload_type,
upload(330),
END OF upload_type.
DATA: itab_upload TYPE STANDARD TABLE OF upload_type,
wa_upload TYPE upload_type.
Data: file type string.
file = 'C:/test.txt'.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
filename = file
filetype = 'ASC'
HAS_FIELD_SEPARATOR = 'X'
TABLES
data_tab = itab_upload
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
Use the sring operations to identify your coloumns.
Regards,
Satish -
In the app "Numbers" I want to paste in many rows in to columns. And each row separated. Now it's getting all in one column when I try to paste.
Fact is that I have a 4 pages list with about 50 rows of single words and I want all that in columnsHey joshuafromisr,
If you resintall iTunes, it should fix the issue. The following document will go over how to remove iTunes fully and then reinstall. Depending on what version of Windows you're running you'll either follow the directions here:
Removing and Reinstalling iTunes, QuickTime, and other software components for Windows XP
http://support.apple.com/kb/HT1925
or here:
Removing and reinstalling iTunes, QuickTime, and other software components for Windows Vista or Windows 7
http://support.apple.com/kb/HT1923
Best,
David -
Setting different Tabel Cell SemanticColor for Multiple Columns of each row
Hi,
I have requirement of setting different colors to different columns for each row based on some condition in table data.
The data to table is coming from model, hence table is mapped to model node and attributes.
I have created Seperate Node CellColorNode with attribue CellClr1 and CellClr2 of type TextView Semantic Color.
Set the calculated, read only attribute to True. Mapped table columns text view to the CellColorNode->CellClr1 and CellColorNode-->CellClr2 correspondingly.
Now, my query is how do i set the colors to CellClr1 and CellClr2 attributes. As I need to set the color for multiple columns of each table row.
Is it in method getColorCellCellClr generated? Any Example Code?Its resolved by following below link
http://scn.sap.com/thread/158286 -
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. -
Summing Selected Rows in Column Depending on Value in Another Column
I'd like to sum only the values in selected rows in a given column depending on the value of another column in the same row. For example, suppose I have a table (please disregard the underscores, needed for correct alignment):
___A____B____C___D
1__5___10___15___0
2_20___25___30___1
3_35___40___45___1
4_50___55___60___0
5__sum(D=1)
In cell B5, I'd like to compute the sum of only rows in column B for which the value of the corresponding column D is 1. In this case B5 would be 65.
How can I do this using functions? Is it possible to do it for a variable range of rows without specifying each row individually?
Thanks,
DaveYou should place your formula to other collumn then calculated ones or in another table. You will be able to calculate whole collumns with: =SUMIF(D;“=1”;B)
Formula for your example is: =SUMIF(D1:D4;“=1”;B1:B4)
VB -
How do I select rows from the same table that have multiple occurances
Hi Everybody,
I am trying to select records from a detail table by grouping it. The table has more than 1 million records and the query is not performing well. The basic question is how to select a distinct record from a table which matches all values in one column and any in the other.
desc SCV
ID NUMBER PK (ID + SCRID)
SCRID NUMBER FK(SC)
ID SCRID
1 1
2 1
3 1
4 2
5 2
6 3
7 4
8 4
desc PROJECTS
ID NUMBER PK
NAME VARCHAR2(100)
ID NAME
1 PROJECT1
2 PROJECT2
3 PROJECT3
4 PROJECT4
desc PJS
ID NUMBER
PROID NUMBER FK (PROJECTS)
SCRID NUMBER FK (SCV(SCRID + SCVID)
SCVID NUMBER
ID PROID SCRID SCVID
1 1 1 1
2 1 1 2
3 1 2 5
4 1 3 6
5 1 4 7
6 2 1 3
7 2 2 4
8 2 2 5
9 2 4 7
There are over 1 million records in PJS.
desc TBP
SCRID NUMBER
SCVID NUMBER
SCRID SCVID
1 1
1 2
1 3
2 4
2 5
3 6
4 7
4 8
The requirement is to select projects that have matching SCRID, SCVID from TBP such that
all distinct SCRID should match and within that and any SCVID match will do. (A "AND" between each SCRID and an "OR" for each SCVID in that SCRID like 'SCRID = 1 AND (SCVID = 1 OR SCVID = 2 OR SCVID = 3) AND SCRID = 2 AND (SCVID =....)
So, for the sample data it should return us PROID = 1
I have few queries written for this:
SELECT PROID FROM PJS,TBP WHERE TBP.SCVID = PJS.SCVID AND TBP.SCRID = 1
INTERSECT
SELECT PROID FROM PJS,TBP WHERE TBP.SCVID = PJS.SCVID AND TBP.SCRID = 2
INTERSECT
SELECT PROID FROM PJS,TBP WHERE TBP.SCVID = PJS.SCVID AND TBP.SCRID = 3
INTERSECT
SELECT PROID FROM PJS,TBP WHERE TBP.SCVID = PJS.SCVID AND TBP.SCRID = 4
This query performs well but the cost is very high, hardcoding, sorting.
The 2nd option is to:
SELECT pjs.PROID proid
FROM TBP tbp,
PJS pjs
WHERE pjs.SCVID = tbp.SCVID
AND pjs.SCRID = tbp.SCRID
GROUP BY pjs.PROID
HAVING COUNT(DISTINCT pjs.SCRID) = (SELECT COUNT(DISTINCT SCRID ) FROM TBP)
This has a low cost but runs slowly.
One more way I tried was with the IN operator like
SELECT DISTINCT PROID FROM PJS A,TBP T WHERE T.SCRID = 1 AND T.SCVID = A.SCVID
AND PROID IN (SELECT PROID FROM PJS A,TBP T WHERE T.SCRID = 2 AND T.SCVID = A.SCVID
AND PROID IN (...SO ON with each DISTINCT SCRID.
Again this involves too much of sorting.
Any help will be appriciated.
Thanks in advance.Hi Andrew,
Use DELETE t_itab statement inside the loop.
I have modified your code. It is perfectly working.See bellow -
LOOP AT it_zmember01 INTO wa_zmember01.
WRITE: / wa_zmember01-mnumber UNDER 'NUMBER',
wa_zmember01-mname UNDER 'NAME',
wa_zmember01-mdob UNDER 'DOB'.
WRITE / '-----------------------------------------------------------------'.
DELETE it_zmember01. " Modified
ENDLOOP.
DELETE it_zmember01. statement inside the loop will delete the current row of the table.
Regards
Pinaki -
Color a column based on value in another column in tableview
I am using a tableview iterator to display data in a bsp page. I want to color a cell in particular column (column 4), when a value in another column (column 2) on that same row is greater than 20. I can color the cell in column 2 but am not able to color the cell in column 4. How can I accomplish this?
This is what I have. Looks like val1 is losing it's value.
CASE p_column_index.
WHEN 2.
ASSIGN p_row_data_ref->* TO <row>.
ASSIGN COMPONENT 'ZTGT' OF STRUCTURE <row> TO <col>.
VAL = <col>.
IF VAL GT '20'.
val1 = p_row_index.
p_style = 'celldesign:CRITICALVALUE_DARK'.
ENDIF.
WHEN 4.
if p_row_index = val1.
p_style = 'celldesign:CRITICALVALUE_DARK'.
endif.
WHEN OTHERS.
do nothing
ENDCASE.The reason val1 is "loosing its' value" is presumably because you have defined it in the method as a local variable. So each time you call the RENDER_CELL_START method it is is newly initialised. So if you make this an instance attribute it will retain its' contents across method calls.
Cheers
Graham Robbo -
Fetching more than one row from a table after selecting one value from the dropdown
Hi Experts,
How can we fetch more than one row from a table after selecting one value from the dropdown.
The scenario is that I have some entries in the dropdown like below
A B C
11256 VID 911256
11256 VID 811256
11256 SONY 11256
The 'B' values are there in the dropdown. I have removed the duplicate entries from the dropdown so now the dropdownlist has only two values.for eg- 'VID' and'SONY'. So now, after selecting 'VID' from the dropdown I should get all the 'C' values. After this the "C' values are to be passed to other methods to fetch some data from other tables.
Request your help on this.
Thanks,
Preeetam Narkhede.Hi Preetam!
I hope I understand your request proberly, since this is more about Java and less about WebDynpro, but if I'm wrong, just follow up on this.
Supposed you have some collection of your original table data stored in variable "origin". Populate a Hashtable using the values from column "B" (let's assume it's Strings) as keys and an ArrayList of whatever "C" is (let's assume String instances, too) as value (there's a lot of ways to iterate over whatever your datasource is, and since we do not know what your datasource is, maybe you'll have to follow another approach to get b and c vaues,but the principle should remain the same):
// Declare a private variable for your Data at the appropriate place in your code
private Hashtable temp = new Hashtable<String, ArrayList<String>>();
// Then, in the method you use to retrieve backend data and populate the dropdown,
// populate the Hashtable, too
Iterator<TableData> a = origin.iterator();
while (a.hasNext()) {
TableData current = a.next();
String b = current.getB();
String c = current.getC();
ArrayList<String> values = this.temp.get(b);
if (values == null) {
values = new ArrayList<String>();
values.add(c);
this.temp.put(b, values);
So after this, you'll have a Hashtable with the B values als keys and collections of C values of this particular B as value:
VID --> (911256, 811256)
SONY --> (11256)
Use
temp.keySet()
to populate your dropdown.
After the user selects an entry from the dropdown (let's say stored in variable selectedB), you will be able to retrieve the collection of c's from your Hashtable
// In the metod you handle the selection event with, get the c value collection
//and use it to select from your other table
ArrayList<String> selectedCs = this.temp.get(selectedB);
// now iterate over the selectedCs items and use each of these
//to continue retrieving whatever data you need...
for (String oneC : selectedCs) {
// Select Data from backend using oneC in the where-Clause or whatever...
Hope that helps
Michael -
JOIN 2 tables that have same column ?
I need to learn how to join two tables that both have the same column name:
tbl1 - idskey
tbl2 - idskey
the idskey column holds a id_number
When I do the JOIN I would like to make sure that only Distinct records are joined from both tables and that any duplicates are removed in the final join. So if:
Tbl1 has a idskey of: 12345
and
Tbl2 has a idskey of: 12345
In the final JOIN I want to remove one of those duplicates.
I actually need to join 3 tables that have the same linking column names for the join, but if I learn how to do this correctly on 2, that will be a start.
10g for db, thanks!Hi,
SELECT DISTINCT and GROUP BY are the most common ways to get unique results from non-unique keys. Exactly how you use them depends on exactly what you want to do.
SELECT DISTINCT guarantees that no two rows in the result set, conisdering all columns, will be identical.
GROUP BY produces one row from a set of rows that have a common feature. The values on that row may be a composite of values from various rows in that set (e.g., an average).
Please post a small, specific example. For instance:
"I have two rows in tbl1 ...
and these fhtee rows in tbl2 ...
Notice how there is one row with idskey=12345 in tbl1 but two such rows in tbl2.
How can I get theses results ...
where only one row has idskey=12345?" -
How to copy one column BLOB value into another column of another database.
How to copy one column BLOB value into another column of another database.
BLOB value contains word document.
I thought of copy the BLOB value into a text file and then update the new column value by the same text in textfile. Will this work?
Is there any other better way to do this?You're welcome
BLOB fields contains binary data. I don't think you can do this
Also if I view the BLOB as text. Can I copy it and insert into the new database.
I think your options are as I said. Datapump or CTAS
Best Regards -
Quering table names containing a value in any column
I searched a bit around this forum and found a solution for how to query the list of all tables
select table_name from user_tables;
However, I do not know how to do this -
I want to find the list of all table names where any of the fields in these tables should have the value containing a number in it.
Say for example I have a database containing many tables Students, Teachers, Principals and many other such 100+ tables. I want to find the list of all tables names which contain the word "ohn" in any of their fields. The string "ohn" MAY be in Employees table under First Name field as John and in Teachers under Nick Name field as Johnny, etc.
So, I do not know what are the columns/field names. I only know that the value of any of these columns will contain the string "ohn" (like '%ohn%'). Now, how do I write a query for this which will give me the table names?
Please assist!Well, this is by no means production code, but it should help you along the way to what you need.
create table test_1
column1 varchar2(100)
create table test_2
column1 number,
column2 varchar2(100),
column3 varchar2(100)
insert into test_1 values ('THIS WILL HAVE MY STRING WITHIN IT');
insert into test_2 values (1, 'WILL NOT QUALIFY', 'NEITHER WILL THIS');
commit;
declare
l_search_string varchar2(100) := '%MY STRING%';
l_count number;
begin
for everything in
select
' with data as (select :x as search_string from dual) select count(*) from ' || table_name || ' where ' || replace(search_string, '-', ' like (select search_string from data) or ') || ' like (select search_string from data) ' as sql_string, table_name
from
select
substr(MAX(SYS_CONNECT_BY_PATH(column_name,'-')), 2) as search_string, table_name
from
select
row_number() over (partition by table_name order by 1) as rn,
table_name,
column_name
from dba_tab_cols
where table_name in ('TEST_1', 'TEST_2')
and data_type in ('CHAR', 'VARCHAR2', 'NVARCHAR2', 'NCHAR', 'CLOB')
group by table_name
start with rn = 1
connect by prior table_name = table_name
and rn = prior rn + 1
loop
execute immediate everything.sql_string into l_count using l_search_string;
if l_count > 0
then
dbms_output.put_line(everything.table_name || ' has ' || l_count || ' rows ');
end if;
end loop;
end;
/Edited by: Tubby on Jan 28, 2010 9:57 PM
I forgot to ask your version number, so if the code i posted doesn't work on your version, you'll have to let us know what your version is .... -
Need to get sequence value in another column in oracle
Hi ALL,
I have sql query as below
select header_id,order_number from oe_order_headers_all.
and data it is displaying as
heder_id order_number
111 500001
121 500400
I need to display another field with some sequence value like as below
id heder_id order_number
1 111 500001
2 121 500400
so how to get sequence value in another column please help me on this.
ThnaksYou can just use ROWNUM Pseudocolumn
select rownum id, header_id,order_number from oe_order_headers_all
Maybe you are looking for
-
Airprint on HP Officejet Pro 8600
I wonder if anybody can help. I recently bought the HP Officejet Pro 8600 mainlyu due to its airprint functionaliy. But now after the setup I cannot get airprint too work. The Apple devices simply does not pick up any printers. I have set the printer
-
How to save video to play on Creative Zen Vision M
My (PC using) friend just bought a Creative Zen Vision M (the competitor to the video iPod). It will play MPEG1, 2, and 4SP and will play MPEG's created in an older version of iMovie (I forget which, it's been a few years). For some reason, the MPEG4
-
Presenter 9 32 bit installer?
I do not see the Adobe Presenter 9 32bit install ?
-
Important Note: Memory Management
If you encounter low memory messages including "Available app space" or "Storage space running out" please check the software on your tablet: 1) Go to Settings 2) Select About Tablet 3) Refer to SW Version If the SW Version on your Ellipsis 7 tablet
-
When role rejected in CUP 5.3 SP8 we get error messages
We have a request with tree roles and when we reject one role and hit the approve button we are asked to do a rsik analysis. After we run that and hit the approve button again we get thiese error messages: Access changed, Risk analysis is invalidated