Returning one row per group
I apologize if this is a duplicate of some other post, but I'm not finding this exact scenario.
Assume that I have a table that looks like this:
select * from PROD_TABLE
PROD DESCRIPTION
1234 CANDLES
1234 CANDLE
1235 BRAKE PADS
1235 BRAKE PAD
(Yes, I know, I know, but it's for a POC, so dirty data will be cleaned up later.)
What I'd like to do is create a select statement that returns two rows from this table, one row for Prod 1234, one row for Prod 1235, and I DON'T CARE which description is returned for the corresponding Prod. For the POC, it's just not important which one is returned.
How can I craft the select statement?
try this
SQL> with t as (select 1234 prod, 'CANDLES' dec from dual union all
2 select 1234 ,'CANDLE' dec from dual union all
3 select 1235 ,'BRAKE PADS' dec from dual union all
4 select 1235 ,'BRAKE PAD' dec from dual)
5 SELECT prod, DEC
6 FROM ( SELECT a.*
7 , ROW_NUMBER ( ) OVER ( PARTITION BY prod ORDER BY prod ) rn
8 FROM t a )
9 WHERE rn = 1
10 /
PROD DEC
1234 CANDLES
1235 BRAKE PADS
SQL>
Similar Messages
-
Query to display one row per group based on highest value
I have the following table and I want to be able to create a query that displays only the highest number based on a group. (see below)
Acode
aname
anumber
a
Jim
40
a
Jim
23
a
Jim
12
b
Sal
42
b
Sal
12
b
Sal
3
Acode
aname
anumber
a
Jim
40
b
Sal
42Multiple ways
using aggregation
SELECT Acode,aname,MAX(anumber) AS anumber
FROM table
GROUP BY Acode,aname
using subquery
SELECT Acode,aname,anumber
FROM table t
WHERE NOT EXISTS (
SELECT 1
FROM table
WHERE Acode = t.Acode
AND aname = t.aname
AND anumber > t.anumber
using analytical function
SELECT Acode,aname,anumber
FROM
SELECT *,ROW_NUMBER() OVER (PARTITION BY Acode, aname ORDER BY anumber DESC) AS Rn
FROM table
)t
WHERE Rn = 1
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
How just return one row of a one to many join..
So I have a one to many join where the SMOPERATOR table has data I need however it has a couple of rows that match the JOIN condition in there. I just need to return one row. I think this can be accomplished with a subquery in the join however have not been able to come up with the right syntax to do so.
So:
SELECT "NUMBER" as danumber,
NAME,
SMINCREQ.ASSIGNMENT,
SMOPERATOR.PRIMARY_ASSIGNMENT_GROUP,
SMOPERATOR.WDMANAGERNAME,
SMINCREQ.owner_manager_name,
SMINCREQ.subcategory, TO_DATE('01-'||TO_CHAR(open_time,'MM-YYYY'),'DD-MM-YYYY')MONTHSORT,
(CASE WHEN bc_request='f' THEN 'IAIO'
WHEN (bc_request='t' and substr(assignment,1,3)<>'MTS') THEN 'RARO'
WHEN (bc_request='t' and substr(assignment,1,3)='MTS') THEN 'M'
ELSE 'U' end) as type
from SMINCREQ
left outer join SMOPERATOR on SMINCREQ.assignment=SMOPERATOR.primary_assignment_group
WHERE SMINCREQ.owner_manager_name=:P170_SELECTION and SMOPERATOR.wdmanagername=:P170_SELECTION
AND open_time BETWEEN to_date(:P170_SDATEB,'DD-MON-YYYY') AND to_date(:P170_EDATEB,'DD-MON-YYYY')
AND
(bc_request='f' and subcategory='ACTIVATION' and related_record<>'t')
OR
(bc_request='f' and subcategory<>'ACTIVATION')
OR
(bc_request='t' and substr(assignment,1,3)<>'MTS')
order by OPEN_TIMeHi,
This sounds like a Top-N Query , where you pick N items (N=1 in this case) off the top of an orderded list. I think you want a separate ordered list for each assignment; the analytic ROW_NUMBER function does that easily.
Since you didn't post CREATE TABLE and INSERT statements for your sample data, I'll use tables from the scott schema to show how this is done.
Say you have a query like this:
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
ORDER BY dname
;which produces this output:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7934 MILLER CLERK 1300
ACCOUNTING 7839 KING PRESIDENT 5000
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
RESEARCH 7902 FORD ANALYST 3000
RESEARCH 7566 JONES MANAGER 2975
RESEARCH 7369 SMITH CLERK 800
RESEARCH 7788 SCOTT ANALYST 3000
SALES 7521 WARD SALESMAN 1250
SALES 7844 TURNER SALESMAN 1500
SALES 7499 ALLEN SALESMAN 1600
SALES 7900 JAMES CLERK 950
SALES 7698 BLAKE MANAGER 2850
SALES 7654 MARTIN SALESMAN 1250Now say you want to change the query so that it only returns one row per department, like this:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
SALES 7499 ALLEN SALESMAN 1600where the empno, ename, job and sal columns on each row of output are all taken from the same row of scott.emp, though it doesn't really matter which row that is.
One way to do it is to use the analytic ROW_NUMBER function to assign a sequence of unique numbers (1, 2, 3, ...) to all the rows in each department. Since each sequence startw with 1, and the numbers are unique within a department, there will be exactly one row per departement that was assigned the numebr 1, and we''ll display that row.
Here's how to code that:
WITH got_r_num AS
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
, ROW_NUMBER () OVER ( PARTITION BY d.dname
ORDER BY e.ename
) AS r_num
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
SELECT dname
, empno, ename, job, sal
FROM got_r_num
WHERE r_num = 1
ORDER BY dname
;Notice that he sub-query got_r_num is almost the same as the original query; only it has one additional column, r_num, in the SELECT clause, and the sub-qeury does not have an ORDER BY clause. (Sub-queries almost never have an ORDER BY clause.)
The ROW_NUMBER function must have an ORDER BY clause. In this example, I used "ORDER BY ename", meaning that, within each department, the row with the first ename (in sort order) will get r_num=1. You can use any column, or expression, or expressions in the ORDER BY clause. You muight as well use something consistent and predictable, like ename, but if you really wanted arbitrary numbering you could use a constant in the analytic ORDER BY clause, e.g. "ORDER BY NULL". -
I have 3 tables - Book, Author, BookAuthorReference
A book can have multiple authors, and when I do straight query I get multiple rows per book
SELECT <columns>
FROM Book b, Author a, BookAuthorReference ba
where ba.BookId = b.BookId and
ba.AuthorId = a.AuthorId
I want to get the results as ONE row per book, and Authors separated by commas, like:
SQL 2008 internals book Paul Randal, Kimberly Tripp, Jonathan K, Joe Sack...something like this
Thank you in advanceThis can by done by straying into XML land. The syntax is anything but intuitive, but it works. And moreover, it is guaranteed to work.
SELECT b.Title, substring(a.Authors, 1, len(a.Authors) - 1) AS Authors
FROM Books b
CROSS APPLY (SELECT a.Author + ','
FROM BookAuthorReference ba
JOIN Authors a ON a.AuthorID = ba.AuthorID
WHERE ba.BookID = a.BookID
ORDER BY ba.AuthorNo
FOR XML PATH('')) AS a(Authors)
Erland Sommarskog, SQL Server MVP, [email protected] -
Hacking application id equals() to allow more than one row per "primary key"
I have a read only entity whose primary key is not the real primary key
on the underlying table. The result is that I get more than one row per
"primary key". This is what I want. However KODO will not allow me do
it, because I am storing the collection in a HashSet() and the equals()
method on the application id object ensures that this set contains no
duplicates (as defined by the application id). At least thats how it
seems to behave.
So, I have hacked the equals() method to do this:
public boolean equals (Object ob)
if (this == ob)
return true;
// Doing this because we expect more than one row from
// REF_CODES for the same domain/shortCode combination.
// This is ok to do (I guess?) as long as we are only
// doing selects using this class.
return false;
Will this hack have any side effects? Is there another option? Like
using a list collection? Is so, which collections are supported?
Thanks,
Mike.The "primary key" I am using it already a compound key of two columns.
The real key on the underlying table is a three column key. But the
problem is that the table represents two different application level
entities. I could deal with it when I was hand-writing SQL (I could do
a distinct for example) but now I am relying on foreign key
relationships since I moved to JDO. Not sure what to do. Best solution
is to rework the table, but there is a lot of legacy code (that other
teams use and maintain) relying on this table. I guess I'll use the
weekend for inspiration ;-)
Steve Kim wrote:
This sounds like a dangerous operation. Even if this works now, I
cannot promise future compatibility... and in fact may result in bad
data (for example in caching both at the PM and PMF level) Is there no
other field that you can reference as part of the primary key? Primary
Keys can be multi columned (e.g. last_name, soc_sec_number)
Mike Hogan wrote:
I have a read only entity whose primary key is not the real primary
key on the underlying table. The result is that I get more than one
row per "primary key". This is what I want. However KODO will not
allow me do it, because I am storing the collection in a HashSet() and
the equals() method on the application id object ensures that this set
contains no duplicates (as defined by the application id). At least
thats how it seems to behave.
So, I have hacked the equals() method to do this:
public boolean equals (Object ob)
if (this == ob)
return true;
// Doing this because we expect more than one row from
// REF_CODES for the same domain/shortCode combination.
// This is ok to do (I guess?) as long as we are only
// doing selects using this class.
return false;
Will this hack have any side effects? Is there another option? Like
using a list collection? Is so, which collections are supported?
Thanks,
Mike. -
OCI - Array-Fetch vs. One-row-per-fetch
Hello guys,
i have a question about the OCI and the possibilities about fetches.
Is it possible to get only one row per fetch without setting the array size to 1?
I have a third party application that shows this behaviour which i have rebuild in sqlplus.
SQL> create table mytest (a number);
SQL> begin
2 for i in 1 .. 1500 loop
3 insert into mytest values (i);
4 end loop;
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> commit;
Commit complete.
SQL> set autotrace traceonly;
-- Now with the default array size of 15 with sqlplus
SQL> select * from mytest;
118 consistent gets
101 SQL*Net roundtrips to/from client
1500 rows processed
-- Now with a bigger array size (150)
SQL> set arraysize 150
SQL> select * from mytest;
17 consistent gets
11 SQL*Net roundtrips to/from client
1500 rows processed
-- Now the behaviour of the third party application
SQL> set arraysize 1
SQL> select * from mytest;
757 consistent gets
751 SQL*Net roundtrips to/from client
1500 rows processed
SQL> set arraysize 2
SQL> select * from mytest;
757 consistent gets
751 SQL*Net roundtrips to/from client
1500 rows processedThe third party application is a c program and i can not take a look at the code.
So as you can see the consistent gets are the same with arraysize 1 and 2. The sql statement which is executed of the c-program is returning a huge amount of data and it seems like it is run with arraysize 1 or 2 or it is executing a different OCI call.
So now is my question:
Which methods does the OCI interface provide to recieve (fetch) data?
- Is it only array fetching (like sqlplus do) or is it possible to return only one row per fetch with a specific call.
I can speed up the query by setting the bigger array-size in sqlplus .. but i want to point the programers to the possibilities with the OCI.
Thanks and Regards
StefanThe following call in OCI can be used to control the fetched rows
MAX_PREFETCH_ROWS is number of rows you want to fetch in one round trip.
(void) OCIAttrSet((dvoid *)DBctx->stmthp, (ub4) OCI_HTYPE_STMT,
(dvoid *)&MAX_PREFETCH_ROWS,(ub4)sizeof(MAX_PREFETCH_ROWS),(ub4) OCI_ATTR_PREFETCH_ROWS, DBctx->errhp); -
Parse column with csv string into table with one row per item
I have a table (which has less than 100 rows) - ifs_tables that has two columns: localtable and Fields. Localtable is a table name and Fields contains a subset of columns from that table. Fields is a comma delimited list: 'Fname,Lname'. It looks like
this:
localtable fields
========= =============
customertable fname,lname
accounttable type,accountnumber
Want to end up with a new table that has one row per column. It should look like this:
TableName ColumnName
============ ==========
CustomerTable Fname
CustomerTable Lname
AccountTable Type
AccountTable AccountNumber
Tried this code but have two issues (1) My query using the Splitfields functions gets "Subquery returned more than 1 value" (2) some of my Fields has hundreds of collumns in the commas delimited list. It will returns "Msg 530, Level 16, State
1, Line 8. The statement terminated. The maximum recursion 100 has been exhausted before statement completion.maxrecursion greater than 100." Tried adding OPTION (maxrecursion 0) in the Split function on the SELECT statment that calls the CTE, but
the syntax is not correct.
Can someone help me to get this sorted out? Thanks
DROP FUNCTION [dbo].[SplitFields]
go
CREATE FUNCTION [dbo].[SplitFields]
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
RETURNS TABLE
AS
RETURN
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split --OPTION ( maxrecursion 0);
GO
IF OBJECT_ID('tempdb..#ifs_tables') IS NOT NULL DROP TABLE #ifs_tables
SELECT *
INTO #ifs_tables
FROM (
SELECT 'CustomerTable' , 'Lname,Fname' UNION ALL
SELECT 'AccountTable' , 'Type,AccountNumber'
) d (dLocalTable,dFields)
IF OBJECT_ID('tempdb..#tempFieldsCheck') IS NOT NULL DROP TABLE #tempFieldsCheck
SELECT * INTO #tempFieldsCheck
FROM
( --SELECT dLocaltable, dFields from #ifs_tables
SELECT dLocaltable, (SELECT [Data] FROM dbo.SplitFields(dFields, ',') ) from #ifs_tables
) t (tLocalTable, tfields) -- as Data FROM #ifs_tables
SELECT * FROM #tempFieldsCheckTry this
DECLARE @DemoTable table
localtable char(100),
fields varchar(200)
INSERT INTO @DemoTable values('customertable','fname,lname')
INSERT INTO @DemoTable values('accounttable','type,accountnumber')
select * from @DemoTable
SELECT A.localtable ,
Split.a.value('.', 'VARCHAR(100)') AS Dept
FROM (SELECT localtable,
CAST ('<M>' + REPLACE(fields, ',', '</M><M>') + '</M>' AS XML) AS String
FROM @DemoTable) AS A CROSS APPLY String.nodes ('/M') AS Split(a);
Refer:-https://sqlpowershell.wordpress.com/2015/01/09/sql-split-delimited-columns-using-xml-or-udf-function/
CREATE FUNCTION ParseValues
(@String varchar(8000), @Delimiter varchar(10) )
RETURNS @RESULTS TABLE (ID int identity(1,1), Val varchar(8000))
AS
BEGIN
DECLARE @Value varchar(100)
WHILE @String is not null
BEGIN
SELECT @Value=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN LEFT(@String,PATINDEX('%'+@Delimiter+'%',@String)-1) ELSE @String END, @String=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN SUBSTRING(@String,PATINDEX('%'+@Delimiter+'%',@String)+LEN(@Delimiter),LEN(@String)) ELSE NULL END
INSERT INTO @RESULTS (Val)
SELECT @Value
END
RETURN
END
SELECT localtable ,f.Val
FROM @DemoTable t
CROSS APPLY dbo.ParseValues(t.fields,',')f
--Prashanth -
Can an Excel Report with Multivalue Custom field list report on one row per task
I have a ECF Multi Value field (MVF) at the Task Level and have created a report. In Excel it wants to add it as a Pivotable, which makes sense and I end up with a row for each MVF. If a Task has 3 MV selected there are 3 rows returned.
I want to see if it will return only one row (row per task).
Example of Result Required
PTask name , MVf Value1, MVF Value2, MVF Value 3.
Build Car X
X
Build Bike X X
Is it possible? is there something in my SQL Query I can do or is there something in Excel I can configure?
Result being Returned
PTask name , MVf Value1, MVF Value2, MVF Value 3.
Build Car X
Build Car X
Build Bike X
Build Bike X
SQL Query
SELECT
MSP_EpmProject_UserView.ProjectOwnerName,
MSP_EpmProject_UserView.ProjectName,
MSP_EpmTask_UserView.TaskName,
MSP_EpmLookupTable.MemberFullValue AS [Item],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'CPT' + '%','X','') AS [CPT],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'TS' + '%','X','') AS [TS],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'CSAs' + '%','X','') AS [CSAs],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'EM' + '%','X','') AS [EM],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'RS' + '%','X','') AS [RS],
Iif(MSP_EpmLookupTable.MemberFullValue LIKE
'%' + 'IS' + '%','X','') AS [IS]
FROM
MSP_EpmProject_UserView INNER JOIN
MSP_EpmTask_UserView ON
MSP_EpmProject_UserView.ProjectUID = MSP_EpmTask_UserView.ProjectUID
LEFT OUTER JOIN
[MSPCFTASK_Service Areas_AssociationView] ON
MSP_EpmTask_UserView.TaskUID = [MSPCFTASK_Service Areas_AssociationView].EntityUID
LEFT OUTER JOIN
MSP_EpmLookupTable ON
[MSPCFTASK_Service Areas_AssociationView].LookupMemberUID = MSP_EpmLookupTable.MemberUID
WHERE datalength(MSP_EpmLookupTable.MemberFullValue) > 0
Andrew PayzeHi Andrew,
I'm not a developer, but I found something in my documentation that could help you. This is a SQL store procedure that returns in an Excel pivot table something like below (GR_test6 being a project and values in the next column being multivalue project ECF
values).
SELECT proj.ProjectName,
lt.MemberFullValue AS 'VLookupField'
FROM dbo.MSP_EpmProject_UserView AS proj
LEFT OUTER JOIN [dbo].[MSPCFPRJ_ProjectECF_AssociationView] AS MVassoc -- view for multi value field
ON proj.ProjectUID = MVassoc.EntityUID
LEFT OUTER JOIN dbo.MSP_EpmLookupTable AS lt
ON MVassoc.LookupMemberUID = lt.MemberUID
order by ProjectName asc
Hope this helps.
Guillaume Rouyre - MBA, MCP, MCTS -
How to return one ROW with Multiple value seperated by Colon in a SQL Query
Hi,
I have a SQL query as mentioned.
select deptno
from deptI want to mofidfy this query, so that this should return me department list with colon delimeted in one ROW.
10:20:30:40.......Thanks,
DeepakIn 10g:
select rtrim(xmlagg(xmlparse(content deptno || ':')).getstringval(), ':') data
from dept;
DATA
10:20:30:40with apologies for the abuse of XML... -
Returning one row in a view(only)
Is there any function that I can use to return just one row from a query?
I tryed the old LIMIT TO from rdb, but its useless...
I´m using a Oracle8Try using "where ROWNUM = 1" for the first row returned by the select
-
SQL Report - PDF Report Printing. How to show one row per page?
Hello
I have successfully created a simple SQL Report.
Than I enabled Report Printing to PDF (default Report Layout).
Export to PDF is working good by default.
Now I want to see one report row per one PDF page. Is it possible?
How I can change the amount of rows per PDF page using default report layout?
I tried to create a User Layout with MSWord Plugin. it's quite suitable for data forms.
But I still did not find a way around for my question.I would create an User Layout (.rtf) with MSWord. Load your XML data and use the table wizzard to put the fields in your document.
Put this code after your last field and before the 'E' (= <?end for-each?> tag):
<?split-by-page-break:?> -
Result Set only returning one row...
When I run the following query in my program, I only get one row.
SELECT * FROM (SELECT * FROM ul_common_log_event WHERE application_name = 'Configuration' ORDER BY cle_id DESC) WHERE ROWNUM <= 500;
However when I run it in TOAD, I get all the rows I am looking for.
Here's my java
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
My record set only contain one row. I am using Oracle 9 OCI driver BTW.
Any ideas? Thanks!Good thinking. That was the first thing I tried. That was not the problem. It turns out that I was stomping my rs object in another method. Problem resolved!
Thanks for the reply! -
Hi ,
I have go three tables. personnel, Personnel_degree, and code_types
here is how they are related . Personnel Stores the person informations like id,name etc. Personnel_degree stores personnel_id, degree_id, , degree_date and code_types stores the code_id and code_name , personnel can belinked to personnel_degree though personel_id and the personnel_degree can be linked though the code_id . Each person can have BS, MS OR PHD , the can have any one of them , two of them or all of them . I want to write a sql query so it brings me the person name and the highest degree he has earned. if John has a PHD degree, then he should not appear under master and BS. Similalry if SAMS has got MS & BS , he should not appear under BS , he should appear under MS only.
Thanks
-FerozYou will need to work out your join conditions. The "Magic" is in the decode statement.
I did it with a decode because I did not know what version you are running, so this will work whether your at 9i or not
Example:
SELECT f_name, DECODE(MAX(DECODE(degree, 'PHD', 3, 'MS', 2, 'BS', 1)), 1, 'BS', 2, 'MS', 3, 'PHD') degree
FROM test
GROUP BY f_name -
This is part of SQL query in FROM clause:
select id, t, phase, time from measurement where phase=1 where id='1234'
This query can return more than one raw, but I need the only one, the latest one
I tried a lot of different stuff but no success!
ThanksGee, not sure if I got you right, but are you really sure that you need to do five (!) outer joins to your METNET table? Dont forget, each join, be it NESTED LOOPS, HASH or MERGE, requires extra CPU and I/O resources
Consider this query as a possible alternative:
SELECT tmh.heatid,
decode(tempcb.phase_id, 1, tempcb.t) cb,
decode(tempcb.phase_id, 2, tempcb.t) cb1,
decode(tempcb.phase_id, 3, tempcb.t) blow1,
decode(tempcb.phase_id, 4, tempcb.t) blow2,
decode(tempcb.phase_id, 5, tempcb.t) blow3
FROM heat_melt_proces_data hmpd,
tmelted_heats tmh,
(select t, sarza, phase_id
from metnet
where phase_id BETWEEN 1 AND 5) tempcb
WHERE hmpd.heatid=tmh.heatid
and tempcb.sarza (+) = tmh.heatid
and (to_char(hmpd.convertertappingendtime , 'YYYY-MM-DD HH24:MI') between '2006-06-10 22:30:01' and '2006-06-12 06:30:00')
order by tmh.heatid, hmpd.convertertappingendtime;And if I got you right regarding your TRANSFERTIME column, this is what you are looking for:
SELECT tmh.heatid,
decode(tempcb.phase_id, 1, tempcb.t) cb,
decode(tempcb.phase_id, 2, tempcb.t) cb1,
decode(tempcb.phase_id, 3, tempcb.t) blow1,
decode(tempcb.phase_id, 4, tempcb.t) blow2,
decode(tempcb.phase_id, 5, tempcb.t) blow3
FROM heat_melt_proces_data hmpd,
tmelted_heats tmh,
(select * from
(select t, sarza, phase_id,
row_number() over
(partition by sarza, phase_id order by transfertime desc) rn
from metnet
where phase_id BETWEEN 1 AND 5)
where rn = 1) tempcb
WHERE hmpd.heatid=tmh.heatid
and tempcb.sarza (+) = tmh.heatid
and (to_char(hmpd.convertertappingendtime , 'YYYY-MM-DD HH24:MI') between '2006-06-10 22:30:01' and '2006-06-12 06:30:00')
order by tmh.heatid, hmpd.convertertappingendtime;
Tip: converting DATEs into VARCHARs and using BETWEEN <varchar-const> AND <varchar-const> is generally an ouch-ouch approach. -
SQL - INSTR - how return a row PER HIT in a record
I need to return the start position for every time my search string is found in the target column of my record. Normally INSTR() will just return a rec for the first hit.
E.g. I need the search for "HIGH" in "3 HIGH ROAD, HIGHMOOR, HIGHBURY" to bring back 3 rows for the start positions 3, 14 and 24.
I can do this with [ignoring the Where instr() > 0 bits]
Select instr(Address, 'HIGH', 1) Start_Pos from Address
union select instr(Address, 'HIGH', 1+instr(Address, 'HIGH', 1)) from Address
union select instr(Address, 'HIGH', instr(Address, 'HIGH', 1+instr(Address, 'HIGH', 1))) from Address;
but that's not very elegant or self extensible (it only finds 3 hits).
Any suggestions please?
Many thanks, Ian Jones (TVP)Hi,
Take a look o this below, and see if help you to resolve your question:
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,1) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,1)
3
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,2) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,2)
6
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,3) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,3)
14
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,4) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,4)
17
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,5) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,5)
24
RPS@ORACLE10> select instr('3 HIGH ROAD, HIGHMOOR, HIGHBURY','H',1,6) from dual;
INSTR('3HIGHROAD,HIGHMOOR,HIGHBURY','H',1,6)
27Cheers
Maybe you are looking for
-
How can I print to my HP OfficeJet 6500 Wireless Printer from my iPhone 4S which used to work (on prior iPhones) before AirPrint printers were even available? (running Mac Lion OS, all software and HP sw updates are all performed) I don't get it, I r
-
CRM_ORDER_MAINTAIN works only in debug mode
Hi Experts, I am currently facing a strange issue. I am trying to add a line item to a service ticket, but the code works only in debug mode. Sample code is given below: lv_product_i-ref_handle = '0000000001'. lv_product_i-ref_guid = lv_header_guid.
-
Urgent - - - help plzzz !!!!!!
HI SAP Gurus, I had been asked to create a new project in XML forms builder. I had created a project and i have specific two issues there, i had created link for email id . when i press the link then i am getting the new window where everytime my nam
-
Can I have CS6 and CC installed at same time?
I am taking editing classes at a community college, which only has CS6. I have CC at home. From all the discussions I've read about non-backward compatability (which does suck btw), I'm thinking I should also have CS6 on my computer. Found CS6 (digit
-
Can connect to wifi, but no internet connection
So, this is my first MacBook. I just bought it yesterday, so I believe I have the latest OS (OS X? Maybe? I'm computer literate with PCs, but really a n00b here, and cannot even find where it would say what OS I'm using). I have tried connecting t