Need help converting MS SQL query into Oracle, Function 'WHERE' issues
SELECT PERS_NBR, PAY_ID, PAY_CODE, LOGICAL_DATE, LOGICAL_DATE AS END_DATE, PCNAMES + REPLICATE(',', 39 - (LEN(PCNAMES) - LEN(REPLACE(PCNAMES, ',', ''))))
AS PC_NAMES_FINAL
FROM (SELECT DISTINCT A.PAY_ID, A.PAY_CODE, A.PERS_NBR, A.LOGICAL_DATE, PCNAMES = substring
((SELECT TOP 10 ',' + PC_NAME + ',' + SUBSTRING(CAST(B.VALUE AS VARCHAR), 0, LEN(CAST(B.VALUE AS VARCHAR)) - 2)
FROM T_PAY_CAT_RECORD B
WHERE B.PERS_NBR = A.PERS_NBR AND
B.LOGICAL_DATE = A.LOGICAL_DATE FOR XML path(''), elements), 2, 500)
FROM T_PAY_CAT_RECORD A, T_PERSON P
WHERE A.PERS_NBR = P.NBR) FINAL
Edited by: 919969 on Mar 9, 2012 3:45 PM
Hello
Like any language you need to understand what the messages coming from the syntax check are saying...
XXXX> SELECT PERS_NBR,
2 PAY_ID,
3 PAY_CODE,
4 LOGICAL_DATE,
5 LOGICAL_DATE AS END_DATE,
6 PCNAMES || LPAD(',', 39 - (LENGTH(PCNAMES) - NVL(LENGTH(REPLACE(PCNAMES,',')),0)),',') AS PC_NAMES_FINAL
7 FROM (
8 SELECT PAY_ID,
9 PAY_CODE,
10 PERS_NBR,
11 LOGICAL_DATE,
12 SUBSTR(
13 RTRIM(XMLAGG(XMLELEMENT(e,PC_NAME || ',' || SUBSTR(VALUE,1,LEN(VALUE) - 2),',').EXTRACT('//text()')),',') PCNAMES
14 2,
15 500
16 )
17 FROM (
18 SELECT A.PAY_ID,
19 A.PAY_CODE,
20 A.PERS_NBR,
21 A.LOGICAL_DATE,
22 A.PC_NAME,
23 ROW_NUMBER() OVER(PARTITION BY A.PERS_NBR,A.LOGICAL_DATE ORDER BY 1) RN
24 FROM T_PAY_CAT_RECORD A,
25 T_PERSON P
26 WHERE A.PERS_NBR = P.NBR
27 )
28 WHERE RN <= 10
29 GROUP BY PAY_ID,
30 PAY_CODE,
31 PERS_NBR,
32 LOGICAL_DATE
33 ) FINAL
34 /
RTRIM(XMLAGG(XMLELEMENT(e,PC_NAME || ',' || SUBSTR(VALUE,1,LEN(VALUE) - 2),',').EXTRACT('//text()')),',') PCNAMES
ERROR at line 13:
ORA-00907: missing right parenthesisIf you use something like SQL*Plus or SQL Developer, they will give you the error stack which will point you to the source of the problem.
It's saying missing right parenthesis. Start by finding out if we've got all out matching brackets. Counting from the start of that statement i.e. SUBSTR on line 12, we have 7 open brackets and 6 close brackets. So there does appear to be a problem with brackets. However if we take a step back and look at lines 12 to 16, this is actually a single statement. It's a call to the SUBSTR function and within it it has calls to RTRIM, XMLAGG etc. For the statement as a whole there are the same number of left and right parenthesis so the problem is related to something else. Something that is leading the syntax check to think it has reached the end of a statement and hasn't found enough closing parethesis.
The issue here appears to be that we have the token PCNAMES at the end of line 13 but syntactically that's not correct. We can't have that token there because it's appearing in the middle of a function call. PCTNAMES is actually a column alias but it's just in the wrong place. We need it to be an alias for the whole expression from line 12 to 16. So make the change and see what happens...
XXXX> select PERS_NBR,
2 PAY_ID,
3 PAY_CODE,
4 LOGICAL_DATE,
5 LOGICAL_DATE AS END_DATE,
6 PCNAMES || LPAD(',', 39 - (LENGTH(PCNAMES) - NVL(LENGTH(REPLACE(PCNAMES,',')),0)),',') AS PC_NAMES_FINAL
7 FROM (
8 SELECT PAY_ID,
9 PAY_CODE,
10 PERS_NBR,
11 LOGICAL_DATE,
12 SUBSTR(
13 RTRIM(XMLAGG(XMLELEMENT(e,PC_NAME || ',' || SUBSTR(VALUE,1,LEN(VALUE) - 2),',').EXTRACT('//text()')),',')
14 2,
15 500
16 ) PCNAMES
17 FROM (
18 SELECT A.PAY_ID,
19 A.PAY_CODE,
20 A.PERS_NBR,
21 A.LOGICAL_DATE,
22 A.PC_NAME,
23 ROW_NUMBER() OVER(PARTITION BY A.PERS_NBR,A.LOGICAL_DATE ORDER BY 1) RN
24 FROM T_PAY_CAT_RECORD A,
25 T_PERSON P
26 WHERE A.PERS_NBR = P.NBR
27 )
28 WHERE RN <= 10
29 GROUP BY PAY_ID,
30 PAY_CODE,
31 PERS_NBR,
32 LOGICAL_DATE
33 ) FINAL
34 /
2,
ERROR at line 14:
ORA-00907: missing right parenthesisNOw we've got a new error. Again it's saying we've got a missing parenthesis but this time on line 14. The issue here is that line 13 is a parameter to the SUBSTR function but there is no comma on the end. What we actually have at the moment is a line that looks like so
RTRIM(XMLAGG(XMLELEMENT(e,PC_NAME || ',' || SUBSTR(VALUE,1,LEN(VALUE) - 2),',').EXTRACT('//text()')),',') 2,Which is just not formed correctly. We need a comma at the end of line 13 to state that this is the end of that line as a parameter.
XXXX> select PERS_NBR,
2 PAY_ID,
3 PAY_CODE,
4 LOGICAL_DATE,
5 LOGICAL_DATE AS END_DATE,
6 PCNAMES || LPAD(',', 39 - (LENGTH(PCNAMES) - NVL(LENGTH(REPLACE(PCNAMES,',')),0)),',') AS PC_NAMES_FINAL
7 FROM (
8 SELECT PAY_ID,
9 PAY_CODE,
10 PERS_NBR,
11 LOGICAL_DATE,
12 SUBSTR(
13 RTRIM(XMLAGG(XMLELEMENT(e,PC_NAME || ',' || SUBSTR(VALUE,1,LEN(VALUE) - 2),',').EXTRACT('//text()')),','),
14 2,
15 500
16 ) PCNAMES
17 FROM (
18 SELECT A.PAY_ID,
19 A.PAY_CODE,
20 A.PERS_NBR,
21 A.LOGICAL_DATE,
22 A.PC_NAME,
23 ROW_NUMBER() OVER(PARTITION BY A.PERS_NBR,A.LOGICAL_DATE ORDER BY 1) RN
24 FROM T_PAY_CAT_RECORD A,
25 T_PERSON P
26 WHERE A.PERS_NBR = P.NBR
27 )
28 WHERE RN <= 10
29 GROUP BY PAY_ID,
30 PAY_CODE,
31 PERS_NBR,
32 LOGICAL_DATE
33 ) FINAL
34 /
T_PERSON P
ERROR at line 25:
ORA-00942: table or view does not existNow we have a new error but this time it's because I don't have the t_person table on my database. Syntactically the statement above is now correct so it should work on your system.
HTH
David
Edited by: Bravid on Mar 12, 2012 10:20 AM
Similar Messages
-
Converting T-SQL proc into Oracle
I need help in converting the following stored procedure into PL/SQL code. Basically I need to know corresponding function names for the various T-SQL constructs below. The parameter @PROC_NUM is passed by the caller with value @@PROCID which is the T-SQL global variable for the ID of the current stored procedure being executed by SQL Server. Thanks in advance for all the help.
CREATE PROCEDURE [dbo].MARS_MPPM_HANDLE_ERROR
@PROC_NUM INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @ERROR_NUMBER INT
DECLARE @ERROR_SEVERITY INT
DECLARE @ERROR_STATE INT
DECLARE @ERROR_PROCEDURE Varchar(1000)
DECLARE @ERROR_LINE INT
DECLARE @ERROR_MESSAGE Varchar(8000)
DECLARE @PROC_NAME Varchar(255)
SELECT
@ERROR_NUMBER = ERROR_NUMBER(),
@ERROR_SEVERITY = ERROR_SEVERITY(),
@ERROR_STATE = ERROR_STATE(),
@ERROR_PROCEDURE = ERROR_PROCEDURE(),
@ERROR_LINE = ERROR_LINE(),
@ERROR_MESSAGE = ERROR_MESSAGE(),
@PROC_NAME = OBJECT_NAME( @PROC_NUM )
IF 50000 = @ERROR_NUMBER
BEGIN
RAISERROR( '%s -> %s', 16, 1, @PROC_NAME, @ERROR_MESSAGE )
END
ELSE
BEGIN
RAISERROR( '%s -> Error Number = %d, Error Severity = %d, Error State = %d, Error Procedure = %s, Error Line = %d, Error Message = %s',
16,
1,
@PROC_NAME,
@ERROR_NUMBER,
@ERROR_SEVERITY,
@ERROR_STATE,
@ERROR_PROCEDURE,
@ERROR_LINE,
@ERROR_MESSAGE )
END
END875311 wrote:
I need help in converting the following stored procedure into PL/SQL code.
Re: How can i rewrite this code into java?
This is true of any language, to adapt to this case
1) Learn T-SQL
2) Understand what that code does, that is, what its job is.
3) Learn PL/SQL.
4) Write PL/SQL code that fulfills the requirements fleshed out in step 2.
The absolutely wrong way to do it is to try a mindless, mechanical translation.
Re: How can i rewrite this code into java?
>
Seriously, you need to go through a Java tutorial from the beginning. Just trying to force another language's syntax onto Java without actually understanding anything about Java, and then posting questions here when you get stuck--questions that you could have and should have answered by doing the tutoria--is a horrible approach.
>
Replace Java with PL/SQL for same answer.
Getting started with PL/SQL
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10766/toc.htm
http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/toc.htm
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e17126/toc.htm -
How to convert an sql query into a recordset?
HI, I'm having a hard time building a locations of service form for users to insert, update the cities, counties, zip codes based on the states selected.
so I found this query that works great if I use basic menus and text boxes, but can't use to make comma separated menus because it is nat a record set.
The problem is that I have a table called zip_codes, with the following fields: state_label, Zip_b, county, city.
zip codes correspond to the cities, counties and states.
example:
Colorado, Colorado Springs, El Paso, 80918
Users make a selection of state or states and the recordset is filtered by user selection.
I manage the part of making a select mutiple drop menu that passes the values to my query page like this.
<form action="litsTA.php"; method="post">
<h3>Choose State(s)</h3>
<p>hold Control key to select multiple states</p>
<select name="States_served[]_<?php echo $cnt1; ?>" multiple="multiple" onchange='showselection()'>
<?php
do {
?>
<option value="<?php echo $row_state['state_label']?>"><?php echo $row_state['state_label']?></option>
<?php
} while ($row_state = mysql_fetch_assoc($state));
$rows = mysql_num_rows($state);
if($rows > 0) {
mysql_data_seek($state, 0);
$row_state = mysql_fetch_assoc($state);
?>
</select>
<p>
<input type="submit" value="submit" />
</p>
</form>
And the query I need to convert into a recordset looks like this
mysql_select_db($database_duitop, $duitop);
$query_TONY = "SELECT * FROM zip_code WHERE state_label IN (";
for ($i=0; $i<=count($state_list)-1; $i++) {
//echo $state_list[$i];
$query_TONY = $query_TONY . "'" . $state_list[$i] . "'";
if ($i < count($state_list)-1) {
$query_TONY = $query_TONY . ", ";
$query_TONY = $query_TONY . ") GROUP BY county ORDER BY state_label, city ASC";
Any way that was my attempt to converting the query into a recordset.
any help, or samples will be appreciated.Use Tcode SQ01.
Give the query name press Enter.
The query will be listed in the table below.
Select the Query => From the Main menu select QUERY => More Functions => Display Report Name.
You will get the program name, now go to Se38 and display the program... -
New To Oracle.. Needs Help:: Conversion from SQL Server to Oracle 11g
I am new to Oracle 11g and badly need the conversion of SQL Server Functions to Oracle.. Sample Pasted Code not working .. end with error.. pls help
Create Table TempT (ID1 Varchar (10),
ID2 Varchar (10)
CREATE OR REPLACE PACKAGE GLOBALPKG
AS
TYPE RCT1 IS REF CURSOR;
TRANCOUNT INTEGER := 0;
IDENTITY INTEGER;
END;
CREATE OR REPLACE FUNCTION fTempT
i IN VARCHAR2 DEFAULT NULL
RETURN GLOBALPKG.RCT1
IS
REFCURSOR GLOBALPKG.RCT1;
BEGIN
OPEN REFCURSOR FOR
SELECT TT.*
FROM TempT TT
WHERE (fTempT.i = ''
OR TT.ID1 = fTempT.i)
RETURN REFCURSOR;
END;
CREATE OR REPLACE FUNCTION fTempTF
i IN VARCHAR2 DEFAULT NULL
RETURN GLOBALPKG.RCT1
IS
REFCURSOR GLOBALPKG.RCT1;
BEGIN
OPEN REFCURSOR FOR
SELECT *
FROM TABLE(fTempT(i))
RETURN REFCURSOR;
END;
LAST FUNCTION ENDs WITH ERROR
Error(13,7): PL/SQL: ORA-22905: cannot access rows from a non-nested table item2. The major purpose is to get a simplest way to create a parameterized function who can return a table like output. 2nd function has no use instead i was testing the result of First Function like thisIf you just want to select from a select, you should use a view not a function.
1. which program is more help ful for writing and executing queries bcoz after using Query Analyzer of Microsoft It seems difficult to work on SQL Developer.
sqlplus? If you are having difficulty learning new tools because of an old one you used, probably best to forget the old one and concentrate on learning the new one because it will be different. This goes for the database itself also.
2. Can DMLs be used within a Function.Yes, you just can't execute the function in another SQL statement if it modifies data and this is a good thing.
3. Can temporary tables be used within a function.Unfortunately yes, but they shouldn't be unless you are in a slowest application competition.
5. Each Function which is a Table Function must be accompanied with Type Definitions?? its a bit longer way of doing the things than SQL ServerThat is why it is better to use views instead, is there any reason you want a select that you can select from inside a function?
SQL Server for last 9 years thats why i refer this toolThat is not in itself a problem, if you try and do what you did in SQLServer in Oracle, that will be a problem though. -
Newbie - need help with a SQL query for a bar chart
Hi,
I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORY
Order by COUNT(PROJECT_ID) DESC
The code from the other app was:
select null link
, FUNCTIONAL_AREA label
, count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
, count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
, count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
from PM_V2
where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
group by FUNCTIONAL_AREA
Order by COUNT(PROJECT_ID) DESC
I'm getting a "Failed to parse SQL query!" error when I try to run validation.
Is this enough info for some assistance? Any help would really be appreciated.
Thanks,
RachelHello,
This is more of an SQL question, rather than specifically APEX-related. It's notable that you say: I'm a new user on APEX with no real SQL knowledgeWhich is fine (we all have to start somewhere, afterall) but it might be worth de-coupling the problem from APEX in the first instance. I'd also strongly recommend either taking a course, reading a book (e.g. http://books.google.co.uk/books?id=r5vbGgz7TFsC&printsec=frontcover&dq=Mastering+Oracle+SQL&hl=en#v=onepage&q=Mastering%20Oracle%20SQL&f=false) or looking for a basic SQL tutorial - it will save you a whole lot of heartache, I promise you. Search the oracle forums for the terms "Basic SQL Tutorial" and you should come up with a bunch of results.
Given that you've copied your query template from another, I would suggest ensuring that the actual query works first of all. Try running it in either:
* SQL Editor
* SQL*Plus
* an IDE like SQL Developer (available free from the OTN: http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html ) or TOAD or similar.
You may find there are syntax errors associated with the query - it's difficult to tell without looking at your data model.
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORYNote that your "order by" clause references a field called "PROJECT_ID", which exists in the old query but you've changed other similar references to "PROJECT_STATUS" - is it possible you've just missed this one? The perils of copy-paste coding I'm afraid... -
Need help in writing SQL query
Hi,
I have a rquirement where I need to convert columns into records.
Table1:
(note: I have around 150 columns i.e period1 to period150)
unit startdate Period1 period2 period3 period4 period5
A 1/1/2011 100 200 300 400 500
Now I need data in below format
UNIT startdate period
A 1/1/2011 100
A 1/1/2011 200
A 1/1/2011 300
A 1/1/2011 500
Please suggest me...
Thanks.With UNPIVOT you can "name" each of your rows using as.
One trick is to "name" the rows to a number - then you can add that number of weeks to your start date - like this:
with t as (
select 'A' unit, DATE '2011-01-01' startdate, 100 period1, 200 period2 ,300 period3, 400 period4 ,500 period5 from dual
select
unit,
startdate + numtodsinterval(week*7,'day') startdate,
qty
from t
unpivot(
qty for week in (
period1 as 0,
period2 as 1,
period3 as 2,
period4 as 3,
period5 as 4
;Theoretically the above should work - but somehow I get a NULL date on my 11.1 instance? And I don't have another version to test with, alas.
But try it and see if it works on your instance ;-) -
Hi Friends,
I am trying to load Employees and their Assignments using APIs.
I have various columns in my staging table like Last Name, First Name, etc., but I need help in writing query in the cursor especially for columns Emp Number and Supervisor Number.
I have data as below
Emp_Number Supervisor_Number
GE0002 GE0064
GE0064 EG0009
EG0009 EG0001
100009 EG0001
EG0001 TU0001
Cursor I write will process the data in the same order as above, but here the problem is...
When it processes first row, it checks for supervisor GE0064 which do not exist and so it errors out.
Similarly for second row, it checks for supervisor EG0009 which again do not exist and so it errors out.
So in order to prevent this, the cursor should process the rows as below
Emp_Number Supervisor_Number
EG0001 TU0001
EG0009 EG0001
GE0064 EG0009
GE0002 GE0064
100009 EG0001
By this way, Supervisor should be defined first as an employee and then it can be used as a supervisor for other employees
is there a way that I can get the output as above(second set of data), when the table has records randomly as above(first set of data)
Appreciate your help!
Thanks,
SrikanthSrikanth wrote:
... but the number of records returned by above query are lot more than number of records in the table.
Why did the number go up?
It's something only you can find out
Maybe some Emp have several Supervisor(s) like
with
t as
(select 'GE0002' Emp,'GE0064' Supervisor from dual union all
select 'GE0064','EG0009' from dual union all
select 'EG0009','EG0001' from dual union all
select 'GE0064','100009' from dual union all
select '100009','EG0001' from dual union all
select 'EG0001','TU0001' from dual
select Emp,Supervisor,lpad('_',3 * (level - 1),'_')||Emp indent
from (select Emp,Supervisor
from t
union all
select supervisor,null
from t tt
where not exists(select null
from t
where emp = tt.supervisor
start with Supervisor is null
connect by prior Emp = Supervisor
EMP
SUPERVISOR
INDENT
TU0001
TU0001
EG0001
TU0001
___EG0001
100009
EG0001
______100009
GE0064
100009
_________GE0064
GE0002
GE0064
____________GE0002
EG0009
EG0001
______EG0009
GE0064
EG0009
_________GE0064
GE0002
GE0064
____________GE0002
Regards
Etbin -
Hi Experts,
I have one requirement as below.
I have two tables say test_1 and test_2 with same structure
Now what i want to accomplish is loop through every record in table table_1 and look for records that have no corresponding entries in table table_2 and delete these rows from table table_1.
Thanks.Hi,
SQL> create table test_1(sno number,name varchar2(10))
2 /
Table created.
SQL> select * from test1
2 /
no rows selected
SQL> desc test1
Name Null? Type
SNO NUMBER
NAME VARCHAR2(10)
SQL> insert into test1 values(1,'vijay')
2 /
1 row created.
SQL> insert into test1 values(2,'vijay')
2 /
1 row created.
SQL> insert into test_1 values(2,'vijay')
2 /
1 row created.
SQL> insert into test_1 values(3,'vi')
2 /
1 row created.
SQL> commit
2 /
Commit complete.
SQL> select * from test1
2 /
SNO NAME
1 vijay
2 vijay
SQL> select * from test_1
2 /
SNO NAME
2 vijay
3 vi
SQL> select * from test1
2 minus
3 select * from test_1
4 /
SNO NAME
1 vijayRegards,
Vijayaraghavan K -
Need help converting Excel IF statement into CASE WHEN statement for Oracle
Hi,
Hope someone can help I have tried various ways of getting this to work, to no avail!
Bascially I have some figures that are minus figures, and I need to add them together to get a movement figure, but I need to treat the minus figures as minus, if that makes sense, rather than the usual... a minus and a minus makes a plus.
For example:- Budget Figure = -1% and Actual Figure = -68% so the movement needs to be -69%.
The IF statement I have been using in Excel is the following:-
=IF(FO110<0,(FP110-(IF(FO110=0,1,FO110)*-1)),FP110-IF(FO110=0,1,FO110))
Which when using the figures as above = -69%
Cell FO = The Budget Figure
Cell FP = The Actual Figure
However, when I created the CASE statement in Oracle, the figure in the query comes back as -0.67, which is oviously not what I want to happen when both actual and budget are minus figures; however when they are a minus and a plus, it works perfectly fine.
Any help on this would be most appreciated!
Kind regards,
AnnmarieHappy I did'n mess something up :)
Nevertheless, don't show it too much around because
case when budget < 0
then actual - case when budget = 0 /* will never happen */
then 1 /* will never happen */
else budget
end * (-1) /* -budget * (-1) remains only */
else actual - case when budget = 0
then 1
else budget
end
endso at least try the following (if case is more readable as decode for you). Let's hope it works as I don't have a Database at hand
case when budget < 0
then actual + budget
else actual - case when budget = 0
then 1
else budget
end
end Regards
Etbin -
i have a table
source table :
create table order(name_a varchar2(100),intid number);
insert into order values('a',1);
insert into order values('b',1);
insert into order values('c',1);
insert into order values('d',1);
insert into order values('e',2);
insert into order values('f',2);
insert into order values('g',2);
i need a query , which result in the below output :
if i look for intid=1 the query should give a,b,c,d
if i look for intid=2 the query should give f,g
ThanksHi,
781649 wrote:
i have a table
source table :
create table order(name_a varchar2(100),intid number);
insert into order values('a',1);
insert into order values('b',1);
insert into order values('c',1);
insert into order values('d',1);
insert into order values('e',2);
insert into order values('f',2);
insert into order values('g',2);Thanks for posting the CREATE TABLE and INSERT statements; it's very helpful.
i need a query , which result in the below output :
if i look for intid=1 the query should give a,b,c,d
if i look for intid=2 the query should give f,gDid you mean <b>e</b>,f,g ?
That's called String Aggregation , and how to do it depends on your version of Oracle, and your exact requirements.
See thie following page for several techniques:
http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
If you're using Oracle 10 (or higher), and it's important that the name_a's be in order in the output, then you can do this:
WITH got_r_num AS
SELECT name_a
, intid
, ROW_NUMBER () OVER ( PARTITION BY intid
ORDER BY name_a
) AS r_num
FROM order_table -- ORDER is not a good table name
WHERE intid IN (1) -- Optional
SELECT intid
, SUBSTR ( SYS_CONNECT_BY_PATH (name_a, ',')
, 2
) AS name_a_list
FROM got_r_num
WHERE CONNECT_BY_ISLEAF = 1
START WITH r_num = 1
CONNECT BY r_num = PRIOR r_num + 1
AND intid = PRIOR intid
;Starting in Oracle 11.2, LISTAGG is better.
This does not assume that you are getting the output only for a single intid at a time. You can get any number of them in a suingle query. Of course, that number can be 1 if that's what you want.
Edited by: Frank Kulash on Mar 24, 2011 12:19 PM -
Need Help with Advanced SQL Query
It's advanced for me, at least. I have three tables that I
need to use:
Product (product_id and product_title are the fields)
shipRegion (shipRegion_ID)
product_shipRegion_shipCharge (product_id, shipRegion_ID,
primaryShipCharge, secondaryShipCharge)
What I am trying to do is create a query that will look for
two things:
1. Any product that is listed in the
product_shipRegion_shipCharge table that has a primary or secondary
ship charge of $0.00 or is NULL.
That part is easy:
SELECT DISTINCT p.product_id, p.product_title
FROM product p
INNER JOIN product_shipRegion_shipCharge pss ON p.product_id
= pss.product_id AND (pss.primaryShipCharge IS NULL OR
pss.primaryShipCharge = 0 OR pss.secondaryShipCharge IS NULL OR
pss.secondaryShipCharge = 0)
WHERE p.display = 1
AND p.price > 0
It's this next part that's tricky for me:
2. Get the product_id and product_title (from the product
table) that does NOT have any entry in the
product_shipRegion_shipCharge table.
I'm guessing that I need to include some kind of LEFT JOIN in
the above query to find out what all of the regions are (from the
shipRegion table) and then see what's missing for each product in
the product_shipRegion_shipCharge table, but I have no idea how to
do it.
Anyone?
JoshThis should be what the query would look like using the left
join:
SELECT product_table.product_id, product_table.product_title
FROM product_table
LEFT OUTER JOIN product_shipRegion_shipCharge
ON product_shipRegion_shipCharge.product_id =
product_table.product_id
WHERE product_shipRegion_shipCharge. product_id IS NULL
SQL Server's query optimizer will probably turn the '...IN
(subquery)' or '...exists (subquery)' into this kind of execution
plan on its own - depending on your table structures. -
Hi,
I have a requirement where I need to show 'F&D' string. I can explain this by below query.
select 'F&D' from dual
but when I run this query, toad prompts me to enter value for &D variable :( But my requirement is to show 'F&D' string.
Can anyone please tell me what modification needs to be done to above query to get string 'F&D' as output.
I know work around for this as below.
select 'F'||chr(38)||'D' from dual
I want permenant solution for this. Can anyone please help me?
Thanks
Shantanusee if below make difference
SQL> select 'F&D' from dual ;
Enter value for d: &D
old 1: select 'F&D' from dual
new 1: select 'F&D' from dual
'F&
F&D
SQL> select 'F'||'&'||'D' from dual ;
'F'
F&D -
SQL Gurus : Need Help in building SQL query
SQL Gurus,
Need your expertise to solve my below problem:
- I have a column that had comma separated data, basically there are the levels in a hierarchy. eg The same column could have the following data:
Row 1: R1L1, R1L2, R1L3
Row 2: R2L1, R2L2
Row 3: R3L1, R3L2, R3L3, R3L4
For assumption purpose lets assume that there are maximum 5 Levels
I want to put this data from this column into another table which holds the levels. I am expecting the output in another table as follows:
Col1____Col2 ____Col3____Col4____Col5
Row 1: R1L1___R1L2____R1L3____null_____null
Row 2: R2L1___R2L2____null_____null_____null
Row 3: R3L1___R3L2____R3L3____R3L4___null
How do i achieve this ? ie coverting the comma separated values in a column to separate columns. The # of values in each columns could be different as I have showb above
Regards,
pkwith t as (
select 'R1L1, R1L2, R1L3' c1 from dual union all
select 'R2L1, R2L2' c1 from dual union all
select 'R3L1, R3L2, R3L3, R3L4' c1 from dual
select substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l + 1,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1) - 2) col1,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1) - 2) col2,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1) - 2) col3,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1) - 2) col4,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 4,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 4,5) + 1) - 2) col5
from (
select c1,
length(c1) - length(replace(c1,',')) + 5 l
from t
COL1 COL2 COL3 COL4 COL5
R1L3 R1L2 R1L1
R2L2 R2L1
R3L4 R3L3 R3L2 R3L1
SQL> SY. -
Need help in this sql query to use Case Statement
hi All,
I have the below query -
SELECT DISTINCT OFFC.PROV_ID
,OFFC.WK_DAY
,CASE
WHEN OFFC.WK_DAY ='MONDAY' THEN 1
WHEN OFFC.WK_DAY ='TUESDAY' THEN 2
WHEN OFFC.WK_DAY ='WEDNESDAY' THEN 3
WHEN OFFC.WK_DAY ='THURSDAY' THEN 4
WHEN OFFC.WK_DAY ='FRIDAY' THEN 5
WHEN OFFC.WK_DAY ='SATURDAY' THEN 6
WHEN OFFC.WK_DAY ='SUNDAY' THEN 7
END AS DOW
,OFFC.OFFC_OPENG_TIME
,OFFC.OFFC_CLSNG_TIME
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID='0000600'
WITH UR;
this query is bringing results in 6 differnt rows with opening and closing time for each day separately. I want to generate the data in one row with each day having opening and closing time, so for 7 days, total 14 columns with opening and closing time. But i am not able to do that using case statement.
can somebody help me in achieving that.
thanks,
iamhereHi,
Welcome to the forum!
That's called a Pivot .
Instead of having 1CASE expression, have 14, one for the opening and one for the closing time each day, and do GROUP BY to combine them onto one row.
SELECT OFFC.PROV_ID
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_OPENG_TIME END) AS mon_opn
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS mon_cls
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_OPENG_TIME END) AS tue_opn
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS tue_cls
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID = '0000600'
GROUP BY offc.prov_id
;This assumes there is (at most) only one row in the table for each distinct prov_id and weekday. If not, what do you want to do? Post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
The staement above works in Oracle 8.1 and up, but there's a better way (SELECT ... PIVOT) available in Oracle 11. What version are you using? (It's always a good idea to include this when you post a question.)
Edited by: Frank Kulash on Jan 6, 2011 8:22 PM -
Need help creating large SQL query
I am trying collect the sum of records that have a cancelled event prior to the Arrive event. The solution needs to be within the Sum function. Any ideas would be helpful
The structure of the table is as follows
1. Record_Num(primary): varchar
2. Event_Type: varchar
3. Time: timestamp
Each record number can contain multiple events, hence the issue with specifiying the time for an event of 'Arrive' and an event of 'Canceled'
This is part of a much bigger query, here's what that looks like:
Select
Sum(Case when di.calltype = 'Missed' then 1 else null end) as "Canceled Prior To Liftoff",
Sum(Case
when dt.eventtype = 'Canceled' Then 1
when
(select to_char(dt.datetimestamp, 'HH:MI:SS')
from progpennstar.dispatchtime dt
where Lower(dt.eventtype) in 'aborted')
< any (select to_char(dt.datetimestamp, 'HH:MI:SS')
from progpennstar.dispatchtime dt
where dt.eventtype in 'Arrive Locale')
Then 1
Else null end) as "Canceled Enroute to Call"
From progpennstar.dispatch di, progpennstar.dispatchtime dt
where di.dateoftransport >= to_date('07/01/2008', 'MM/DD/YYYY') and
di.dateoftransport <= to_date('09/30/2008', 'MM/DD/YYYY') and
di.dispatch_id = dt.dispatch_idto the op: I think SomeoneElse already got the solution, I just want to add a few minor points. You can replace the ANY construct (which is rarely used) with a simple comparison. In general ANY constructs are more difficult to understand. Check if the correct logic is applied.
SELECT SUM(CASE
WHEN di.calltype = 'Missed' THEN 1
ELSE NULL
END) AS "Canceled Prior To Liftoff"
,SUM(CASE
WHEN dt.eventtype = 'Canceled' THEN 1
WHEN dt.eventtype = 'Aborted'
AND exists (SELECT null
FROM dispatchtime dt2
WHERE dt2.eventtype IN 'Arrive Locale'
AND dt2.dispatch_id = di.dispatch_id
AND dt.datetimestamp < dt2.datetimestamp /* this is the new comparison */
THEN 1
ELSE NULL
END) AS "Canceled Enroute to Call"
FROM dispatch di,
dispatchtime dt
WHERE di.dateoftransport >= to_date('07/01/2008', 'MM/DD/YYYY')
AND di.dateoftransport < to_date('09/30/2008', 'MM/DD/YYYY') /* Carefull! I changed <= to <. Do you want to include the full last day or only midnight? */
AND di.dispatch_id = dt.dispatch_id;I also changed the alias of the remaining subquery so that different aliases are used.
Edited by: Sven W. on Dec 11, 2008 1:01 PM
Maybe you are looking for
-
Can i put movies from my ipod onto my itunes?
I have some movies on my ipod that i want to put onto my itunes, and was wondering if i could do this. please help.
-
Connection of iPhone to PC failes due to missing necessary software
although I have the updated Itunes software on my PC I receive a failure message when I connect the iPhone to my PC saying that I have not the necessary software on my iPhone. On the other side my iPhone is recognized by my internet explorer and is v
-
Animate in Mocha AE doesnt support scandinavian letters
Hello there Seems like theres an issue with linking to Mocha AE. After i select a file, go to animate->track in mocha, it says file not found. The dialog box shows the file name, with scandinavian letters - ä and ö - replaced with for example, ÂÅQ. S
-
JNI call to find stability of file
We receive files from third-party servers and these files are written to the disk in a windows machine. I am trying to find out how I can find out if the file is completely written to disk. I don't know the size of the file. Once the file is written
-
1. What is difference between WCF REST SERVICE(and not WCF) and WebAPI? 2. When we should one over another? Deepak Talele Ph: 91-9158413830 Email: [email protected], [email protected]