WITHOUT USING ROW_NUMBER FUNCTIONS IN T-SQL
INPUT:-
CUST_ID
GIFT_ID
100
10
100
20
100
30
200
10
200
20
200
30
300
20
OUTPUT:-
CUST_ID
GIFT_ID
SEQ
100
10
1
100
20
2
100
30
3
200
10
1
200
20
2
200
30
3
300
20
1
santoshbangalore
THANK YOU SO MUCH FOR YOUR ANS? BUT MY INPUT TABLE A CONTAIN ONLY TWO COLUMN'S
CUST_ID,GIFT_ID
AND IN OUT PUT I NEED THE ABOVE OUTPUT WITH
CUST_ID,GIFT_ID,ROW_NUMBER AS SHOWN ABOVE?
santoshbangalore
Similar Messages
-
Hello every one, can I rewrite the following query without using the 'ROW_NUMBER() OVER ' part.
The query is supposed to pull out the records whose CODE is not NULL and has most
recent date for UPDATE_DATE . The reason I wanted to do this is, When I embed this query
in between many other queries along with JOINs, My oracle server is unable to execute. So, I thought
its better to supplant 'ROW_NUMBER() OVER ' logic with something else and try it. .
SELECT a.* FROM
(SELECT b.*, ROW_NUMBER() OVER (PARTITION BY b.PIDM
ORDER BY b.UPDATE_DATE DESC) AS Rno
FROM
SELECT *
FROM SHYNCRO WHERE CODE IS NOT NULL
)b
)a
WHERE a.Rno = 1Hi,
You didn't write over 150 lines of code and then start testing it, did you?
Don't.
Take baby steps. Write as little as pssiblem test that. Debug and test again until you have something that does exactly what you want it to do.
When you have somehting that works perfectly, take one baby step. Add a tiny amount of code, maybe 1 or 2 lines more, and test again.
When you do get an error, or wrong results, you'll have a much better idea of where the problem is. also, you won't be building code on a flimsy foundation.
If you need help, post the last working version and the new version with the error. Explain what you're trying to do in the new version.
The error message indicates line 133. It looks like line 133 of your code is blank. Does your front end allow completely blank lines in the middle of a query? SQL*Plus doesn't by default; you have to say
SET SQLBLANKLINES ONto have a completely blank line in SQL*Plus. (However, lines containing nothing but at commnet are always allowed.)
You may have noticed that this site normally doesn't display multiple spaces in a row.
Whenever you post formatted text (such as indented code) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
The 4 people who posted small code fragments for you to read all did this. It would be so much easier for people to read your humongeous query if it were formatted. -
Use of ROW_NUMBER() function in PL/SQL
I have a Table Emp with the following Structure
SQL> desc emp
Name Null? Type
EMPNO NUMBER(2)
ENAME VARCHAR2(50)
HIREDATE DATE
DEPTNO NUMBER(2)
If I write a following query on this table
SQL> SELECT deptno, hiredate, record_id
2 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
3 OVER (ORDER BY hiredate) AS record_id
4 FROM emp)
5 WHERE record_id >= 2
6 AND record_id <=5;
The Result I get is
DEPTNO HIREDATE RECORD_ID
10 22-NOV-01 2
10 22-NOV-01 3
10 22-NOV-01 4
10 22-NOV-01 5
But if I put this query in a cursor in a PL/SQL block. The
pl/sql does not compiles and gives me the following address
SQL> DECLARE
2 CURSOR c_my IS
3 SELECT deptno, hiredate, record_id
4 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
5 OVER (ORDER BY hiredate) AS record_id
6 FROM emp)
7 WHERE record_id >= 2
8 AND record_id <=5;
9 BEGIN
10 FOR c_rec IN c_my LOOP
11 dbms_output.put_line(c_rec.ename);
12 END LOOP;
13 END;
14 /
OVER (ORDER BY hiredate) AS record_id
ERROR at line 5:
ORA-06550: line 5, column 13:
PLS-00103: Encountered the symbol "(" when expecting one of the
following:
, from
Question: Can you please tell me how I can use the ROW_NUMBER()
function in PL/SQL. I need to use this for selecting the correct
range of records for Pagination on a website.
Thanks in advance
PrashantAs Andrew said, PL/SQL hasn't caught up with the newer bits of
SQL. I have heard that in 9i, they will be the same, but in 8i
there are still things that you can do in SQL that you cannot do
directly in PL/SQL, such as the new functions like ROW_NUMBER.
However, you can use NDS as a work around. The following does
the same as what you posted:
SET SERVEROUTPUT ON
DECLARE
TYPE c_my_type IS REF CURSOR;
c_my c_my_type;
TYPE c_rec_type IS RECORD
(deptno emp.deptno%TYPE,
ename emp.ename%TYPE,
hiredate emp.hiredate%TYPE,
record_id INTEGER);
c_rec c_rec_type;
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id
FROM (SELECT deptno, ename, hiredate,
ROW_NUMBER() OVER
(ORDER BY hiredate)
AS record_id
FROM emp)
WHERE record_id >= 2
AND record_id <= 5';
OPEN c_my FOR v_sql;
LOOP
FETCH c_my INTO c_rec;
EXIT WHEN c_my%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (c_rec.ename);
END LOOP;
END;
However, you stated that you need it for selecting the correct
range of records for pagination on a website. For that, you
will want something more like this:
CREATE OR REPLACE PACKAGE package_name
AS
TYPE c_my_type IS REF cursor;
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4);
END package_name;
CREATE OR REPLACE PACKAGE BODY package_name
AS
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4)
IS
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id'
|| ' FROM (SELECT deptno, ename, hiredate,'
|| ' ROW_NUMBER() OVER'
|| ' (ORDER BY hiredate)'
|| ' AS record_id'
|| ' FROM emp)'
|| ' WHERE record_id >= :a'
|| ' AND record_id <= :b';
OPEN c_my FOR v_sql
USING p_record_id1, p_record_id2;
END procedure_name;
END package_name; -
I want single update query without use the function.
I want to update sells_table selling_code field with max date product_code from product table.
In product table there is multiple product_code date wise.
I have been done it with below quey with the use of function but can we do it in only one update query
without use the function.
UPDATE sells_table
SET selling_code = MAXDATEPRODUCT(ctd_vpk_product_code)
WHERE NVL(update_product_flag,0) = 0 ;
CREATE OR REPLACE FUNCTION HVL.maxdateproduct (p_product IN VARCHAR2) RETURN NUMBER
IS
max_date_product VARCHAR2 (100);
BEGIN
BEGIN
SELECT NVL (TRIM (product_code), 0)
INTO max_date_product
FROM (SELECT product_code, xref_end_dt
FROM product
WHERE TO_NUMBER (p_product) = pr.item_id
ORDER BY xref_end_dt DESC)
WHERE ROWNUM = 1; -- It will return only one row - max date product code
EXCEPTION
WHEN OTHERS
THEN
RETURN 0;
END;
RETURN max_date_product;
END maxdateproduct;
Thanks in Advance.Hi,
Something like this.
update setlls_table st
set selling_code =(select nvl(trim(product_code)) from
(select product_code
, rank() over (partition by item_id order by xref_end_dt DESC) rn
from product
) pr
where rn =1
and pr.item_id = st.ctd_vpk_product_code
) where NVL(update_product_flag,0) = 0 ;As such not tested due to lack of input sample.
Regards
Anurag Tibrewal. -
Max value without using max() function
Hi
Is there any way to get the max value from a table without using MAX() function
Thankswell if you think about it i'm sure you'll find a solution
what does max(field) means, it simply is the value of the field where no other value of the same field that is > than this value exists.
consider the following :
table TAB(
fld NUMBER(5));
translate the logic and you'll have
select a.fld from TAB a where NOT EXISTS(select b.fld from TAB b where b.fld>a.fld) and rownum=1;
of course there are better ways i'm sure, you'll just have to figure'em out. -
Need to take rownum highest value without using grouping functions
Hi
I want to display highest value in the rownum column and customer details without using grouping functions like max or count
this below query gives me all rownum values and customer details
SELECT ROWNUM ROWNUM_1, CUSTOMER_NO, CUSTOMER_NAME, CUSTOMER_DOJ, CUSTOMER_MOBILENO FROM CUSTOMER;
can any one help me.The above query won't work as it's missing "from" cluase in the inner select statement.
And even if corrected it willl print rownum values thrice: value "1",max_rownum, max_rownum followed by customer details.
Below is the simple query to retrieve max row_num along with the corresponding customer details.
select * from (SELECT ROWNUM ROWNUM_1, CUSTOMER_NO, CUSTOMER_NAME, CUSTOMER_DOJ, CUSTOMER_MOBILENO FROM CUSTOMER order by rownum_1 desc) where rownum<=1 ; -
Alternate without using regexp_replace function
SELECT
REGEXP_REPLACE(phone_number,
'([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',
'(\1) \2-\3') "REGEXP_REPLACE"
FROM employees;
is there any alternate without using regexp_replace function.........Another way
(eliminating instr function.. as your problem focusses on a fixed length)
WITH t AS (SELECT '112.345.6789' str FROM DUAL),
tt AS (SELECT REPLACE (str, '.') str FROM t)
SELECT '('
|| SUBSTR (str, 1, 3)
|| ') '
|| SUBSTR (str, 4, 3)
|| '-'
|| SUBSTR (str, 7)
FROM tt;
Cheers,
Manik. -
Print a DayName without using Date functions
Hi,
I have an assignment like without using any date functions i should print a calendar.
Below is the code without using any datefunctions like dateadd, datediff, datename a calendar has been generated for month and year entered. I want a week name for the dates like sunday ... monday etc.
I can take any date from calendar as reference and calculate based on that date.
ex: today is 2/20/2014 thursday . Next 7days again will be thursday, same way before 7days will be thursday.
I need to loop in below procedure and get weekname.
Plz help in the code,
I am using SQL server 2008
IF OBJECT_ID ('dbo.Calendar1') IS NOT NULL
DROP PROCEDURE dbo.Calendar1
GO
CREATE PROCEDURE [dbo].Calendar1 --4,1991
@month int,
@Year int
AS
BEGIN
declare
@startdateofMonthYear date,
@EnddateofMonthYear Date
Set @startdateofMonthYear=(Select cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'01')
Set @EnddateofMonthYear = (SELECT case when @month IN (1,3,5,7,8,10,12) then cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'31'
when @month IN(4,6,9,11) then cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'30'
else cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+(CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN '29' else '28' End)
End)
;WITH CTE_DatesTable
AS
Select 1 daysint, Cast(SUBSTRING(cast(@startdateofMonthYear as varchar(20)),1,7) + '-'+CAST(1 as varchar(2)) as DATE) Calendardates
UNION ALL
SELECT daysint+1,Cast(SUBSTRING(cast(@startdateofMonthYear as varchar(20)),1,7) + '-'+CAST(daysint+1 as varchar(2)) as DATE) Calendardates
FROM CTE_DatesTable
WHERE daysint<=
(SELECT case when @month IN (1,3,5,7,8,10,12) then 31
when @month IN(4,6,9,11) then 30
else (CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN 29 else 28 End)
End)-1
Select
[DWDateKey]=Calendardates,
[DayDate]=daysint,
[MonthNumber]=@Month,
[MonthName]=Case when @month = 1 then 'January'
when @month = 2 then 'February'
when @month = 3 then 'March'
when @month = 4 then 'April'
when @month = 5 then 'May'
when @month = 6 then 'June'
when @month = 7 then 'July'
when @month = 8 then 'August'
when @month = 9 then 'September'
when @month = 10 then 'October'
when @month = 11 then 'November'
when @month = 12 then 'December'
End,
[Year]=@Year
From CTE_DatesTable
END
bhavanaIn the above code, where do i pass the year and month?
(Select 2000 YearID
Union All
Select YearID +1 From cte where YearID <2100
In above condition from 2000 year its displaying.
If i want in 90's year , Day name will not be correct.
Deepa -
Not able to use a function inside a sql in a form, Why ??
Here SERIAL_NUM is a function, this sql work fine in TOAD and SQLPLUS but inside the form iam getting error saying "function serial_num cannot be used in a sql" Why is it like that ?? Is there anyother way to execute this sql ?
cursor c1 is
SELECT msn.ATTRIBUTE7 Order_No,
SERIAL_NUM(i.SERIAL_NUMBER) Serial_No,
msn.ATTRIBUTE5 Firmware,
msn.ATTRIBUTE15 Site_Pref
FROM atrd.INSTALLER_INFO i,
mtl_serial_numbers msn
where SERIAL_NUM(i.SERIAL_NUMBER)=msn.SERIAL_NUMBERHere is the process I did. My oim version is 9.1.0.2
1) Created java program in IBM RAD and compiled it.
2) Created jar file using jar -cvfm class-files command.
3) Copied the jar file to javatasks folder.
4) Tried to use this jar in adapter then got "Failed because null" and sometimes "Server could not load class" messages. most of the time i am getting "failed because null" message.
Compiled using javac command also without using this tool and created still no luck.... -
Select extra row without using UNION ALL in pl/sql
Hi,
Can anyone tell me how to select extra row without using UNION or UNION ALL in pl/sql. Actually I want to have my o/p of query as partitioned by designation and ordered by salary and than one extra row which will contain the highest salary in a particular salary. My table has first_name,emp_id,designation and salary column. And I wnt the o/p as.
Mohinish,12212,SI,46000
Ram,11212,SSI,47000
Shyam,12133,SI,48000
Rick,9898,SI,46000
Rocky,12312,SSI,56000
Sariq,23948,SI,43000
Suman,12789,HR,49000
Sampy,12780,SI,46000
Parna,11111,HR,50000
Now the o/p should be.
Mohinish,12212,SI,46000
Rick,9898,SI,46000
Sariq,23948,SI,43000
Shyam,12133,SI,48000
Shyam,12133,SI,48000
Ram,11212,SSI,47000
Rocky,12312,SSI,56000
Rocky,12312,SSI,56000
Suman,12789,HR,49000
Parna,11111,HR,50000
Parna,11111,HR,50000
Thanks in AdvanceYou don't have to do a UNION or UNION ALL in PL/SQL but you would need to in SQL to get the desired output:
with data_recs
as (select 'Mohinish' first_name,12212 emp_id,'SI' designation,46000 salary from dual union
select 'Ram',11212,'SSI',47000 from dual union
select 'Shyam',12133,'SI',48000 from dual union
select 'Rick',9898,'SI',46000 from dual union
select 'Rocky',12312,'SSI',56000 from dual union
select 'Sariq',23948,'SI',43000 from dual union
select 'Suman',12789,'HR',49000 from dual union
select 'Sampy',12780,'SI',46000 from dual union
select 'Parna',11111,'HR',50000 from dual)
select first_name, emp_id, designation, salary from data_recs union all
select s.first_name, s.emp_id, s.designation, s.salary
from (select first_name,
emp_id,
designation,
salary,
row_number() over (partition by designation order by salary desc) high_salary
from data_recs
order by designation, salary) s
where s.high_salary = 1
order by designation, salary;
FIRST_NAME EMP_ID DESIGNATION SALARY
Suman 12789 HR 49000
Parna 11111 HR 50000
Parna 11111 HR 50000
Sariq 23948 SI 43000
Rick 9898 SI 46000
Mohinish 12212 SI 46000
Sampy 12780 SI 46000
Shyam 12133 SI 48000
Shyam 12133 SI 48000
Ram 11212 SSI 47000
Rocky 12312 SSI 56000
Rocky 12312 SSI 56000 -
Using max function in PL/SQL
VERY URGENT...
Am new to oracle...
I've written a package that display gif images in form of histogram/bar chart. using html,
I need to use max function to display values proportionately.
please help. i need to complete this assignment by 2/9/00 by 10.00 am at the latest. I've half written a function but I don't know if there's a simpler way fo doing this. html enabledFirst of all Thanks to all gentlemen who replied ..many thanks ...
Tried the ROW_NUMBER() option but still it is taking time...have given output for the query and tkprof results as well. Even when it doesn't fetch any record ( this is a valid cased because the input header id doesn't have any workflow request submitted & hence no entry in the wf_items table)..then also see the time it has taken.
Looked at the RANK & DENSE_RANK options which were suggested..but it is still taking time..
Any further suggestions or ideas as to how this could be resolved..
SELECT 'Y', 'Y', ITEM_KEY
FROM
( SELECT ITEM_KEY, ROW_NUMBER() OVER(ORDER BY BEGIN_DATE DESC) RN FROM
WF_ITEMS WHERE ITEM_TYPE = 'xxxxzzzz' AND ROOT_ACTIVITY = 'START_REQUESTS'
AND SUBSTR(ITEM_KEY,1,INSTR(ITEM_KEY,'-') - 1) = :B1
) T WHERE RN <= 1
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 1 0.00 1.57 0 0 0 0
Fetch 1 8700.00 544968.73 8180 8185 0 0
total 2 8700.00 544970.30 8180 8185 0 0
many thanks -
Hello guys,
I'm writing a stored procedure which tries to convert a string representing a number to a fixed size number(with 2 positions fraction). For example, if the input was "15,456" the result would become 15.45.
I was able to aschieve this ussing the CAST function within a query as follows:
select cast ('15,456' as number(15,2)) from dual; -- (the comma in my case is configured as fraction separator). The previous query executes OK using a query analyzer like SQL Plus.
However, when I try to use the same function within a stored procedure, it will complain about the number's size (15,2) and wont compile.
v_importe_ingresado := CAST('15,456' AS NUMBER(15,2));
Error output: PLS-00103 found '(' but expected one of the following: .)@%
When removing the (15,2) it compiles ok
¿Any clue?
I will appreciate any help.
Thanks in advance,
Bernabé¿Any clue?¿¿¿Over complication???
SQL> select round(15.456, 2), trunc(15.456, 2) from dual
2 /
ROUND(15.456,2) TRUNC(15.456,2)
15.46 15.45
SQL> Cheers, APC
Blog : http://radiofreetooting.blogspot.com/ -
Count the no.of rows without using count function
Hi,
How to count the no.of rows without using the count function?
Thanks,they won't be 100% accurate. You're correct, Bluefrog, but the same goes for doing a count(*) (depending on the size of the table, ofcourse):
the table being queried might be under DML (deletes/inserts), and the next count(*) might give different results.
Both approaches will never be 100% accurate.
But simply selecting num_rows will be much much faster than doing a count(*).
Counting the number of rows always reminds me of this ongoing discussion, by the way:
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:127412348064#14136093079164 ;)
Usually knowing the number of records by approximatly is sufficient, imo. 1000000 or 1000007 records: I don't care, don't need to know that.
I've never needed to know the exact number of records in a table in my code, or been given a requirement that forced me to. -
Generating sequence Using row_number function.
Hello All,
I want to know if we can create sequence using row_number .
I know we can create sequence using row_number but I want to start my sequence from 001, can we create using row_number?
It will be great, If I can get a faster response.
Thanks in advance.user13034857 wrote:
Hello All,
I want to know if we can create sequence using row_number .
I know we can create sequence using row_number but I want to start my sequence from 001, can we create using row_number?
It will be great, If I can get a faster response.
Thanks in advance.
SQL> set pagesize 60
SQL> SELECT TO_CHAR (ROWNUM, '000') Seq, s.table_name
2 FROM user_tables s
3 WHERE ROWNUM <= 20;
SEQ TABLE_NAME
001 ICOL$
002 CON$
003 UNDO$
004 PROXY_ROLE_DATA$
005 FILE$
006 UET$
007 IND$
008 SEG$
009 COL$
010 CLU$
011 PROXY_DATA$
012 TS$
013 BOOTSTRAP$
014 FET$
015 CCOL$
016 USER$
017 OBJ$
018 TAB$
019 CDEF$
020 OBJERROR$
20 rows selected.
SQL>
SQL> SELECT TO_CHAR (ROW_NUMBER () OVER ( ORDER BY dept),
2 '000')
3 Seq,
4 empno,
5 ename,
6 dept
7 FROM Emp;
SEQ EMPNO ENAME DEPT
001 2345 zxcv 10
002 1111 qwer 10
003 1234 asdf 20
004 5657 ghjk 20
005 3125 tyui 30
006 2134 zxvnb 30
007 8907 cvmn 30
7 rows selected.
SQL>
SQL> -
Need help in using sleep function in pl/sql
Hi,
need help:
I have a condition where i want to validate total_pass=total_fail and
I want to use the sleep function in a pl/sql where i want to wait for 2 minutes ie.checking
whether total_pass=total_fail based upon class_id .
I have the data in the table as:
CLASS_ID TOT_PASS TOT_FAIL
1 10 10
2 5 4
3 6 6
4 7 5
Any help will be needful for meI'm not quite sure what you are lookg for here, but whatever it is, your code as posted won't do it. You will never break out of the WHILE r_Class.Tot_Pass = r_Class.Tot_Fail loop, since these values will never change because you never get the next record form the cursor.
From your original data, it looks like your cursor will return multiple rows which implies to me that you want to fetch the first row from the cursor, check if tot_pass = tot_fail, if they are equal, sleep for two minutes then get the next row. This does not make sense to me. Once the select in the cursor is executed, the data it returns will not change due to Oracle's read consistency model, so there seems to me no point in the sleep.
The other alternative I can see is that you want to check all the returned rows, and if tot_pass = tot_fail for one of the rows (or possibly for all of the rows), then you want to sleep and try again.
If you can explain in words what it is you are trying to accomplish, someone will be able to point you to a solution.
John
Maybe you are looking for
-
Recently my ipod was stolen and had to replace my computer too now i can't find my music in itunes
recently my ipod was stolen and also had to replace my computer too i can't find my itunes purchased music
-
Can't see package body in SQL Developer version 3.1
Hello, Have been scouring the boards and google for this issue for quite some time now. I think I have discovered the issue, but would like to see if a work around exists. Problem: I am unable to view packages, procs, VIEW DDl, etc. of other users. W
-
Bulk import error - Missing required attribute fullname
Folks, I am having trouble trying to bulk import some users. I have the following file for import (cut down from what I really want to import): command,user,waveset.resources,password.password,password.confirmpassword,global.firstname,global.lastname
-
Hi all, Can anyone suggest me about Whats the default parameter in key commit trigger? Thanking you Seshu
-
Hi, Yesterday I was stupid enough to perform Repair Permissions from a Tiger system onto Leopard. Results: -All new folders are read only for me, but read-write for "system". I have to assign myself as read-write every time. -All non-system fonts are