Complex SQL query help
Hi,
I was wondering if I could have some help with the query I have below for this general data set, please? I need to do it in a single SQL statement. We're currently running Oracle 10g. The piece I'm struggling with is identifying that the person has all the items in a collection and to include the collection in the resulting collection of items.
persons_items
person item
Ted cup
Ted saucer
Ted plate
Ted fork
Alice book
Alice thimble
Alice knife
Alice cup
Joe cup
Joe saucer
Joe plate
Joe knife
Joe fork
Joe spoon
Jessica spatula
Jessica dish
collections
collection_name item
crockery cup
crockery saucer
crockery plate
cutlery knife
cutlery fork
cutlery spoon
Query:
What single items and collections does Ted have? fork, crockery
What single items and collections does Alice have? book, thimble, knife, cup
What single items and collections does Joe have? crockery, cutlery
What single items and collections does Jessica have? spatula, dish
Thanks in advance.
Pat
Expanding on Brendan's solution...
For 11g:
SQL> ed
Wrote file afiedt.buf
1 WITH person_items AS (
2 SELECT 'Ted' person, 'cup' item FROM DUAL UNION
3 SELECT 'Ted', 'saucer' FROM DUAL UNION
4 SELECT 'Ted', 'plate' FROM DUAL UNION
5 SELECT 'Ted', 'fork' FROM DUAL UNION
6 SELECT 'Alice', 'book' FROM DUAL UNION
7 SELECT 'Alice', 'thimble' FROM DUAL UNION
8 SELECT 'Alice', 'knife' FROM DUAL UNION
9 SELECT 'Alice', 'cup' FROM DUAL UNION
10 SELECT 'Joe', 'cup' FROM DUAL UNION
11 SELECT 'Joe', 'saucer' FROM DUAL UNION
12 SELECT 'Joe', 'plate' FROM DUAL UNION
13 SELECT 'Joe', 'knife' FROM DUAL UNION
14 SELECT 'Joe', 'fork' FROM DUAL UNION
15 SELECT 'Joe', 'spoon' FROM DUAL UNION
16 SELECT 'Jessica', 'spatula' FROM DUAL UNION
17 SELECT 'Jessica', 'dish' FROM DUAL
18 ), collections AS (
19 SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
20 SELECT 'crockery', 'saucer' FROM DUAL UNION
21 SELECT 'crockery', 'plate' FROM DUAL UNION
22 SELECT 'cutlery', 'knife' FROM DUAL UNION
23 SELECT 'cutlery', 'fork' FROM DUAL UNION
24 SELECT 'cutlery', 'spoon' FROM DUAL
25 ), person_item_colls AS (
26 SELECT pi.person, pi.item, co.collection_name,
27 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
28 FROM person_items pi
29 LEFT JOIN collections co
30 ON co.item = pi.item
31 )
32 select person, listagg(collection_name,',') within group (order by collection_name) as collections
33 from (
34 SELECT DISTINCT person, collection_name
35 FROM person_item_colls
36 WHERE collection_name IS NOT NULL
37 AND n_col > 1
38 UNION ALL
39 SELECT person, item
40 FROM person_item_colls
41 WHERE collection_name IS NULL
42 OR n_col = 1
43 )
44* group by person
SQL> /
PERSON COLLECTIONS
Alice book,cup,knife,thimble
Jessica dish,spatula
Joe crockery,cutlery
Ted crockery,forkFor 10g:
SQL> ed
Wrote file afiedt.buf
1 WITH person_items AS (
2 SELECT 'Ted' person, 'cup' item FROM DUAL UNION
3 SELECT 'Ted', 'saucer' FROM DUAL UNION
4 SELECT 'Ted', 'plate' FROM DUAL UNION
5 SELECT 'Ted', 'fork' FROM DUAL UNION
6 SELECT 'Alice', 'book' FROM DUAL UNION
7 SELECT 'Alice', 'thimble' FROM DUAL UNION
8 SELECT 'Alice', 'knife' FROM DUAL UNION
9 SELECT 'Alice', 'cup' FROM DUAL UNION
10 SELECT 'Joe', 'cup' FROM DUAL UNION
11 SELECT 'Joe', 'saucer' FROM DUAL UNION
12 SELECT 'Joe', 'plate' FROM DUAL UNION
13 SELECT 'Joe', 'knife' FROM DUAL UNION
14 SELECT 'Joe', 'fork' FROM DUAL UNION
15 SELECT 'Joe', 'spoon' FROM DUAL UNION
16 SELECT 'Jessica', 'spatula' FROM DUAL UNION
17 SELECT 'Jessica', 'dish' FROM DUAL
18 ), collections AS (
19 SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
20 SELECT 'crockery', 'saucer' FROM DUAL UNION
21 SELECT 'crockery', 'plate' FROM DUAL UNION
22 SELECT 'cutlery', 'knife' FROM DUAL UNION
23 SELECT 'cutlery', 'fork' FROM DUAL UNION
24 SELECT 'cutlery', 'spoon' FROM DUAL
25 ), person_item_colls AS (
26 SELECT pi.person, pi.item, co.collection_name,
27 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
28 FROM person_items pi
29 LEFT JOIN collections co
30 ON co.item = pi.item
31 )
32 select person, ltrim(sys_connect_by_path(collection_name,','),',') as collections
33 from (
34 select person, collection_name, row_number() over (partition by person order by collection_name) as rn
35 from (
36 SELECT DISTINCT person, collection_name
37 FROM person_item_colls
38 WHERE collection_name IS NOT NULL
39 AND n_col > 1
40 UNION ALL
41 SELECT person, item
42 FROM person_item_colls
43 WHERE collection_name IS NULL
44 OR n_col = 1
45 )
46 )
47 where connect_by_isleaf = 1
48 connect by person = prior person and rn = prior rn + 1
49* start with rn = 1
SQL> /
PERSON COLLECTIONS
Alice book,cup,knife,thimble
Jessica dish,spatula
Joe crockery,cutlery
Ted crockery,fork
Similar Messages
-
Hello,
My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
Thanks in advance
Daniel HHello,
My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
Thanks in advance
Daniel H -
I'm having trouble with an SQL query. I've created a simple logon page wherein a user will enter their user name and password. The program will look in an Access database for the user name, sort it by Date/Time modified, and check to see if their password matches the most recent password. Unfortunately, the query returns no results. I'm absolutely certain that I'm doing the query correctly (I've imported it directly from my old VB6 code). Something simple is eluding me. Any help would be appreciated.
private void LogOn() {
//make sure that the user name/password is valid, then load the main menu
try {
//open the database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:LawOffice2000", "", "");
Statement select = con.createStatement();
String strTemp = "Select * From EMPLOYEES Where INITIALS = '" + txtUserName.getText() + "' Order By DATE Desc, TIME Desc";
ResultSet result = select.executeQuery(strTemp);
while(result.next()) {
if (txtPassword.getPassword().toString() == result.getString("Password")) {
MenuMain.main();
else {
System.out.println("Password Bad");
System.out.println(txtUserName.getText());
System.out.println(result.getString("Password"));
break; //exit loop
//close the connection
con.close(); }
catch (Exception e) {
System.out.println("LawOfficeSuite_LogOn: " + e);
return; }
}The problem is here: "txtPassword.getPassword().toString() == result.getString("Password"))"
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same characters), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus == -
SQL Query Help - Is this possible or impossible????
Hi guys,
I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
For example,
I have 2 tables
The first table is:
1) COMPANY create table company (manufacturer varchar2(25),
date_established date,
location varchar2(25) );My sample test date is:
insert into company values ('Ford', 1902, 'USA');
insert into company values ('BMW', 1910, 'Germany');
insert into company values ('Tata', 1922, 'India');The second table is:
2) MODELS create table models (manufacturer varchar(25),
model varchar2(25),
price number(10),
year date,
current_production_status varchar2(1) ) ;My sample test data is:
insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
insert into models values ('Ford', 'Galaxy', 12000, 2008, 0);
insert into models values ('Ford', 'Escort', 10000, 1992, 1);
insert into models values ('BMW', '318', 17500, 2010, 0);
insert into models values ('BMW', '535d', 32000, 2006, 0);
insert into models values ('BMW', 'Z4', 10000, 1992, 0);
insert into models values ('Tata', 'Safari', 4000, 1999, 0);
insert into models values ('Tata', 'Sumo', 5500, 1996, 1);
insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
SELECT
com.manufacturer,
com.date_established,
com.location,
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
mod.current_production_status
FROM
company com,
models mod
WHERE
mod.manufacturer = com.manufacturer
and com.manufacturer IN ('Ford', 'BMW', 'Tata')
and mod.current_production_status IN (1,0)
ORDER BY
mod.current_production_status DESCWhat I want the query to output is this:
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
BMW 1910 Germany - - - 0
Tata 1922 India Sumo 5500 1998 1If current_production_status is 1 it means this particular model has been discontinued
If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
So the query should output the one row where current_production_status is 1 for each manufacturer.
If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
My query as it is above will output all the records where current status is 1 or 0 like this
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
Tata 1922 India Sumo 5500 1998 1
Ford 1902 USA - - - 0
Ford 1902 USA - - - 0
BMW 1910 Germany - - - 0
BMW 1910 Germany - - - 0
BMW 1910 Germany - - - 0
Tata 1922 India - - - 0
Tata 1922 India - - - 0However this is not what I want.
Any ideas how I can achieve the result I need?
Thanks!
P.S. Database version is '10.2.0.1.0'Hi Vishnu,
Karthiks query helped...
But this is the problem I am facing...
SELECT
com.manufacturer,
com.date_established,
com.location,
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
mod.current_production_status
FROM
company com,
models mod
WHERE
mod.manufacturer = com.manufacturer
and com.manufacturer = 'Ford'
and mod.current_production_status IN (1,0)
ORDER BY
mod.current_production_status DESCThe value of:
and com.manufacturer = 'Ford'will be dependent on front end user input....
When I run the query above I get all the rows where current_production_status is either 1 or 0.
I only require the rows where current_production_status is 1.
So if I amend it to look like this:
and mod.current_production_status = 1This works....
BUT if a user now passes in more than one manufacturer EG:
and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
So like this:
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
BMW 1910 Germany - - - 0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
Thanks you so much!
This is really driving me insane :-( -
Complex SQL Query in BPEL DB Adapter
Hi,
Is it possbile to write a complex query in BPEL DB Adapter using "Custom SQL Query"?
I would like to write an IF ELSE condition in the DB Adapter similar what is given below..
IF((SELECT COUNT(*) FROM F5898001 WHERE CT58SRCNME = 'CA_TEST' AND CTJOBNAME = '12345' AND CTEDBT = 'EDBT' AND CTEDSP = 'B') < 1)
BEGIN
insert into f5898001 (CTJOBNAME,CTEDSP,CTEDBT,CT58SRCNME) VALUES (#jobname, #edsp, #edbt, #srcnme)
END.In a single pass no.
You could use a DB link to perform select and return result to BPEL process variable. Put a switch decision depending on result in variable that calls a DB Adapter to perform the insert.
Wouldn't be in a single transaction and not very elegant, but might be a way round. -
Hi,
I require help for sql query. The query will be like
"SELECT * FROM XYZ WHERE TEXT = 'h*s' "
and the results will be come like
“his”
“homes”
“houses”
“horses”,
“horticulturalists”
“herbaceous”.
Thanks,
KapilHello,
SELECT *
FROM XYZ
WHERE TEXT LIKE ('h%s');Regards
Edited by: OrionNet on Feb 2, 2009 12:33 AM -
SQLEception using Complex SQL Query with Java Studio Creator2 Build(060120)
I am evaluating Java Studio Creator2 for a WEB base application project that will be making SQL queries to an Oracle Database but I have stumble into a problem using complex SQL queries.
I am getting an SQLException "org.apache.jasper.JasperException: java.lang.RuntimeException: java.sql.SQLException: [sunm][Oracle JDBC Driver][Oracle]ORA-00923: FROM keyword not found where expected". I looks like it cut my sql.
The SQL that I am trying to execute is
Select part_name
from table1, table2
where table1.part_nbr = table2.part_nbr
and table2.row_add_dt = (select max(table3.row_add_dt)
from table3
where table3.ser_part_id =table2.ser_part_id)
This is a valid query that it is using 2 different selects to get a part number.
If posible, point me to the best solution were I will be able to make complex SQL queries like the one above and bigger.
Is there any way that I can read an SQL query file instead of inserting the SQL query string into the setCommand()?I have read that document looking for some anwsers on how to make this kind of query. If I try the query that I have above in the query editor ,the query editor will cut off from the last select that is between ().
I beleave, there is a work around using the inner joint or outter join command. I will try them to see If I get the corrent result. If not, then I have to keep on asking for possible solutions.
Anyway, someone in the Creator Team should take a note in adding something like a special criteria in the Add Query Criteria Box for cases like the one I have. The special criteria will be like using another select/from/where to get some result that will be compare.
Girish, Are you in the Sun Creator Team? -
Obtain rows from a complex sql query
Hi to all, please somebody who can help me, my scenario is as next:
One table like next
Reservation (table)
Boat (string)
reservation (date)
class (string)
room1_cod (int)
room1 (int)
room2_cod (int)
room2 (int)
room3_cod (int)
room3 (int)
In room(x)_cod , I am saving a client code, in the room(x) , I am saving the price of the room for that client.
example:
LUSITANIA, 2014-3-1, MEDIUM, 0, 0, 145, 345, 0, 0 = client 145 ocupied room 2 paying $345
LUSITANIA, 2014-2-1, MEDIUM, 145, 345, 0, 0, 0, 0 = client 145 ocupied room 1 paying $345
LUSITANIA, 2014-1-1, MEDIUM, 0, 0, 0, 0, 145, 345 = client 145 ocupied room 3 paying $345
how would like to make an sql query for filter :
(Boat, reservation, class... with a reservation start date and finish date and with an specific "client code" find and filter this code into room1_cod , room2_cod and room3_cod .... and maybe do a temporarly table with rows containing (Boat, Reservation,
Class, "client_code" , "client_pay" )
Resulting LIKE:
LUSITANIA, 2014-3-1, MEDIUM, 145, 345
LUSITANIA, 2014-2-1, MEDIUM, 145, 345
LUSITANIA, 2014-1-1, MEDIUM, 145, 345
Please I need your guidance. TKSPlease take a look
SELECT Boat, reservation, class,
case
when room1_cod>0 then 1
when room2_cod>0 then 2
when room3_cod>0 then 3
end as Room,
case
when room1_cod>0 then room1_cod
when room2_cod>0 then room2_cod
when room3_cod>0 then room3_cod
end as client_code,
case
when room1>0 then room1
when room2>0 then room2
when room3>0 then room3
end as client_pay
from
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-3-1',121) AS reservation, 'MEDIUM' AS class, 0 AS room1_cod, 0 AS room1, 145 AS room2_cod, 345 AS room2, 0 AS room3_cod, 0 AS room3 ---//client 145 ocupied room 2 paying $345
union all
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-2-1',121) AS reservation, 'MEDIUM' AS class, 145 AS room1_cod, 345 AS room1, 0 AS room2_cod, 0 AS room2, 0 AS room3_cod, 0 AS room3 --//= client 145 ocupied room 1 paying $345
union all
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-1-1',121) AS reservation, 'MEDIUM' AS class, 0 AS room1_cod, 0 AS room1, 0 AS room2_cod, 0 AS room2, 145 AS room3_cod, 345 AS room3 --//= client 145 ocupied room 3 paying $345
) as Reservation
----Better table design would eliminate multiple columns for each room/client code/rate like the following
SELECT
Boat, reservation, class,
Room,
room_cod as client_code,
room_rate as client_pay
from
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-3-1',121) AS reservation, 'MEDIUM' AS class, 2 AS room, 145 AS room_cod, 345 AS room_rate ---//client 145 ocupied room 2 paying $345
union all
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-2-1',121) AS reservation, 'MEDIUM' AS class, 1 AS room, 145 AS room_cod, 345 AS room_rate --//= client 145 ocupied room 1 paying $345
union all
SELECT 'LUSITANIA' AS Boat, CONVERT(DATE,'2014-1-1',121) AS reservation, 'MEDIUM' AS class, 3 AS room, 145 AS room_cod, 345 AS room_rate --//= client 145 ocupied room 3 paying $345
) as Reservation
thanks for you effort, best regards -
Sql query - help reqd (new)
Hi,
I have follwing dataset
"herb with garden"
"garden without herb"
"herb with zbc"
"garden with pqr"
Now i want sql query like
select * from table where text1 = "herb and garden"
This should populate
herb with garden
garden without herb
And
select * from table where text1 = "herb or garden"
This should populate
"herb with garden"
"garden without herb"
"herb with zbc"
"garden with pqr"SQL> with t
2 as
3 (
4 select 'herb with garden' str from dual union all
5 select 'garden without herb' str from dual union all
6 select 'herb with zbc' str from dual union all
7 select 'garden with pqr' str from dual
8 )
9 select *
10 from t
11 where lower(str) like '%herb%'
12 and lower(str) like '%garden%'
13 /
STR
herb with garden
garden without herb
SQL> with t
2 as
3 (
4 select 'herb with garden' str from dual union all
5 select 'garden without herb' str from dual union all
6 select 'herb with zbc' str from dual union all
7 select 'garden with pqr' str from dual
8 )
9 select *
10 from t
11 where lower(str) like '%herb%'
12 or lower(str) like '%garden%'
13 /
STR
herb with garden
garden without herb
herb with zbc
garden with pqr -
Continuation-Please help with a complex sql query
Hi all,
Thanks a lot for your suggestions and inputs in the last thread of this post.
With the help of your suggested approach,i went ahead and was able to get some more data in the format as needed..I worked on gradually adding one table after another exactly as the data is required stepwise.But,still I am facing issues with displaying them.
there are many issues I am not able to do and would appreciate if you please have a look at my latest modified SELECT given below and help me writing it to get the display as needed.
Below,is the attempted query i tried out using your inputs.But,am stuck and need your help in writing it.
**Here,there is 1 ->MANY lines for the t_objective_id--->This has many learning_record_ids which i want to group by the unique objective_id.
Also,prior to that,there is a tplan_id---->which has MANY t_objective_id's
SELECT DECODE (LAG (firstname, 1, 0) OVER (ORDER BY firstname),
firstname, ' ',
firstname
) firstname,
DECODE (LAG (emplid, 1, 0) OVER (ORDER BY emplid),
emplid, ' ',
emplid
) emplid,
DECODE (LAG (tplan_name, 1, 0) OVER (ORDER BY tplan_name),
tplan_name, ' ',
tplan_name
) tplan_name,
tplan_id,
DECODE (LAG (activities, 1, 0) OVER (ORDER BY activities),
activities, ' ',
activities
) activities,
activities,
--activities,
DECODE (LAG (t_objective_id, 1, 0) OVER (ORDER BY t_objective_id),
t_objective_id, ' ',
t_objective_id
) t_objective_id,
completed_activities,required_credits,
DECODE (LAG (learning_record_id, 1, 0) OVER (ORDER BY learning_record_id),
learning_record_id, ' ',
learning_record_id
) learning_record_id,
catalog_item_name,catalog_item_type
FROM (SELECT test_cp.firstname, test_op.emplid, tp.tplan_name,tp.tplan_id,FN_TP_GET_CMPLTD_ACT_CNT(tp.tplan_id,test_lp.lp_person_id,'1862') activities,
test_tpo.t_objective_id,
( fn_tp_obj_comp_req_act_cdt (test_lp.lp_person_id,
tp.tplan_id,
test_tpo.t_objective_id,
tp.is_credit_based
+ fn_tp_obj_comp_opt_act_cdt (test_lp.lp_person_id,
tp.tplan_id,
test_tpo.t_objective_id,
tp.is_credit_based
) completed_activities,test_tpo.required_credits,lr.learning_record_id,lr.catalog_item_name,lr.catalog_item_type
FROM test_learning_plan test_lp,
test_training_plan tp,
test_person test_cp,
test_org_person test_op,test_tp_learning_activity test_tplplr,
test_tp_objective test_tpo,test_learning_record lr,test_train_obj_activity tpobjact
WHERE test_lp.lp_person_id = '1862188559'
AND test_cp.person_id = test_lp.lp_person_id
AND tp.tplan_id = 'tplan200811200632352287621599'
AND test_tpo.t_objective_id = tpobjact.t_objective_id
AND test_lp.LP_CATALOG_HIST_ID = tp.tplan_id
AND test_tplplr.tp_lp_lr_id =test_lp.learning_plan_id
AND test_tplplr.activity_lp_lr_id = lr.learning_record_id
AND lr.LR_CATALOG_HISTORY_ID = tpobjact.activity_id
AND test_op.o_person_id = test_cp.person_id
AND test_tpo.tplan_id = tp.tplan_id)
If we see the outer SELECT ---then one of the main issues is for EACH t_objective_id----->There are n learning_record_ids.
But,this select only shows 1 learning_record_id for each objective_id which is wrong.
Similarly,the data displayed isnot proper.
Below is the way I am getting the data now from the above SELECT.
Note:- FIRSTNAME is not correctly displayed.
FIRSTNAME EMPLID TPLAN_NAME TPLAN_ID ACTIVITIES ACTIVITIES_1
001 TP1 tplan1 5 5
TESTNAME tplan1 5
Continuation of the other columns of the same rows--**couldnt paste it properly so.
T_OBJECTIVE_ID COMPLETED_ACTIVITIES REQUIRED_CREDITS LEARNING_RECORD_ID CATALOG_ITEM_NAME CATALOG_ITEM_TYPE
obj1 1 5 lr1 C1 Course
obj2 4 4Something like this might solve your problem ->
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for Linux: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
Elapsed: 00:00:00.00
satyaki>
satyaki>
satyaki>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7521 WARD SALESMAN 7698 22-FEB-81 226.88 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1815 1400 30
7788 SCOTT ANALYST 7566 19-APR-87 598.95 20
7839 KING PRESIDENT 17-NOV-81 7260 10
7844 TURNER SALESMAN 7698 08-SEP-81 2178 0 30
7876 ADAMS CLERK 7788 23-MAY-87 159.72 20
7900 JAMES CLERK 7698 03-DEC-81 1379.4 30
7902 FORD ANALYST 7566 03-DEC-81 5270.76 20
7934 MILLER CLERK 7782 23-JAN-82 1887.6 10
7566 Smith Manager 7839 23-JAN-82 1848 0 10
7698 Glen Manager 7839 23-JAN-82 1848 0 10
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7599 BILLY ANALYST 7566 10-JUN-09 4500 30
12 rows selected.
Elapsed: 00:00:00.00
satyaki>
satyaki>
satyaki>
satyaki>
satyaki>select decode(lag(job,1,null) over(order by job),'CLERK','CK',
2 'SALESMAN', 'SM',
3 'ANALYST','AL',
4 'BO') res
5 from emp;
RE
BO
AL
AL
AL
CK
CK
CK
BO
BO
BO
SM
RE
SM
12 rows selected.
Elapsed: 00:00:00.01
satyaki>
satyaki>
satyaki>select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
2 'SALESMAN', 'SM',
3 'ANALYST','AL',
4 'BO')) res
5 from emp;
select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
ERROR at line 1:
ORA-30483: window functions are not allowed here
Elapsed: 00:00:00.01
satyaki>
satyaki>select MAX(res)
2 from (
3 select decode(lag(job,1,null) over(order by job),'CLERK','CK',
4 'SALESMAN', 'SM',
5 'ANALYST','AL',
6 'BO') res
7 from emp
8 );
MA
SM
Elapsed: 00:00:00.00
satyaki>
satyaki>Regards.
Satyaki De. -
hi guys
i have sample data as mentioned below... need to find the duplicate rows where cd=cd and dt1=dt1 and tm1 difference should be less than or equal to 4 hrs..
i can get the data with the query written below but my problem is that i am not allowed to use in-built sql server function... can you help me in writing the same without using in-built function...
CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
select * From #t
WITH MyCTE (rn,id, dt1, tm1, cd)
AS(
select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
,BASE.dt1
,BASE.tm1
,base.cd base_cd
,LEAD.dt1 LEAD_START_DATE
,LEAD.tm1 LEAD_START_TIME
,lead.cd lead_cd
--,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
FROM MyCTE BASE
LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
AND BASE.rn = LEAD.rn+1
) b
)cif this code will not work for you then not sure if there are any other options
Converted the CTE into an actual temp table.
CTE and barebones T-SQL code are included in the script below.
CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
select * From #t
;WITH MyCTE (rn,id, dt1, tm1, cd)
AS(
select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
,BASE.dt1
,BASE.tm1
,base.cd base_cd
,LEAD.dt1 LEAD_START_DATE
,LEAD.tm1 LEAD_START_TIME
,lead.cd lead_cd
--,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
FROM MyCTE BASE
LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
AND BASE.rn = LEAD.rn+1
) b
)c
select * into #copy From #t order by id, cd, dt1, tm1
alter table #copy add seqno int identity(1,1)
select distinct y.id,y.cd,y.dt1,y.tm1,y.seqno,case when z.cd is not null then 'Duplicate_Req' else '' end dt123
from #copy y
left outer join
(select a.id,a.cd,a.dt1,a.tm1
From #copy a
left outer join #copy b
on a.id = b.id
and a.cd = b.cd
and a.dt1 = b.dt1
where a.seqno > b.seqno
and abs(datediff(MINUTE,b.tm1,a.tm1)) <= 240) z
on y.id = z.id
and y.cd = z.cd
and y.dt1 = z.dt1
and y.tm1 = z.tm1
order by y.dt1,y.tm1
drop table #copy
drop table #t -
I am trying to take a complex query that I was running inside of C# code and turn it into a stored proc so that it performs much better. I was doing quite a bit of looping in C# code because I am most familiar with that but I know it ain't the best way to do things. Basically my query does the following:
-Query a table to get a set of table names
-loop over that set of table names to query another table to get some info
-use that info to query another table to find out if there are any results
-if there are results add those to a table to be returned to the caller
The issue I am having is that I don't know how to build the return table so I can pass it back to the calling code. All i need to know is the names of the tables that had at least one hit in my big query.
I am kind of new to this so I may have some things in here that are completely bizarre. I won't be offended if you rip it apart. I know that my out SYS_REFCURSOR will not work as is. The part that says 'SELECT OBJECTID really needs to be telling me the name of the table and not OBJECTID. I want to jam all these table names into a resultset which would really just be a temp table that I create with one field (TableName).
I know it's a lot to ask but if anyone can look at any part of this and give me suggestions I would greatly appreciate it. I'm struggling slowly through PL/SQL trying not to do dumb things when there are easier ways. There is probably a way for me to get rid of this loop but I think I need the dynamic part because I am querying different tables. Thank you very much
CREATE OR REPLACE PROCEDURE "CREAM_USER"."ENVELOPE_INTERSECT"
pMINX IN NUMBER,
pMAXX IN NUMBER,
pMAXY IN NUMBER,
pMINY IN NUMBER,
pRESULTSET OUT SYS_REFCURSOR
AS
BEGIN
DECLARE
SQLSTR VARCHAR2(700);
theLayerID NUMBER;
cursor gi is SELECT TABLE_NAME, OWNER FROM VIEW_GEOINDEXER_TABLES WHERE GEOINDEXED = 1;
theTABLE_NAME varchar2(160);
qTheTABLE_NAME varchar2(160);
theOWNER varchar2(32);
BEGIN
for iLayer in gi loop
theTABLE_NAME := iLayer.TABLE_NAME;
theOWNER := iLayer.OWNER;
qTheTABLE_NAME := '''' || theTABLE_NAME || '''';
theOWNER := '''' || theOWNER || '''';
SQLSTR := 'SELECT LAYER_ID FROM SDE.LAYERS WHERE OWNER = ' || theOWNER || ' AND TABLE_NAME = ' || qTheTABLE_NAME || '';
EXECUTE IMMEDIATE SQLSTR INTO theLAYERID;
SQLSTR := 'SELECT OBJECTID FROM ' || theTABLE_NAME || ' WHERE SHAPE IN
SELECT FID FROM F' || theLayerID || ' WHERE
(' || pMINX || ' >= EMINX AND ' || pMINX || ' <= EMAXX)
OR
(' || pMAXX || ' >= EMINX AND ' || pMAXX || ' <= EMAXX)
AND
(' || pMINY || ' >= EMINY AND ' || pMINY || ' <= EMAXY)
OR
(' || pMAXY || ' >= EMINY AND ' || pMAXY || ' <= EMAXY)
OR
(' || pMINX || ' <= EMINX AND ' || pMAXX || ' >= EMAXX)
AND
(' || pMINY || ' <= EMINY AND ' || pMAXY || ' >= EMAXY)
OPEN pRESULTSET FOR SQLSTR;
END LOOP;
END;
END ENVELOPE_INTERSECT;Looks like you are using dynamic sql but, not using bind variables.
Check out this link (try to ignore the original question) and see how the third post shows you how to use dyanmic sql using the 'USING' construct.
dynamic SQL
HTH,
Rahul. -
Hello,
I need help with SQL... My database version is Oracle 10g Release 1.2.
I have two table with the exact same structure as follows...
create table t1(cust_id number(5), zone_number number(2), part_number varchar2(10))
create table t2(cust_id number(5), zone_number number(2), part_number varchar2(10))
I need a query that would give me two counts per pairs of customer between t1 and t2..
1.Count of part_number matches between the same zones in table 1 and table 2 for pairs of customers
for Customer 1 and 10 for zone 1 this total shoulb be 2 because between cust 1 and 10 for Zone 1 there are two part number matches A and B.
for Customer 1 and 10 for zone 2 this total shoulb be 0 because between cust 1 and 10 for Zone 2 there are no part number matches
for Customer 1 and 20 for zone 1 this total shoulb be 0 because between cust 1 and 20 for Zone 1 there are no part number matches
for Customer 1 and customer 20 zone 2 this total shoulb be 0 because between cust 1 and 20 for Zone 2 there is one part number matches , which is 'F'
for Customer 1 and customer 20 zone 3 this total shoulb be 0 because there is no zone 3 for Customer 1
same way
.. cust 2 and cust 10 Zone 1 counts and zone2 counts
.. for 2 and cust 20 zone 1, 2, and 3 counts
2. Total unique Part nmbers between the same zones for pairs of customers in table 1 and table2
for example
unique part numbers between cust 1 and 10 for zone 1 are A,B and C so the count should be 3
unique part numbers between cust 1 and 10 for zone 2 are B,F, D and E so the count should be 3
unique part numbers between cust 1 and 20 for zone 1 are A,B,C and G so the count should be 4
and so on so forth
insert into t1 values(1, 1, 'A')
insert into t1 values(1, 1, 'B')
insert into t1 values(1, 1, 'C')
insert into t1 values(1, 2, 'B')
insert into t1 values(1, 2, 'F')
insert into t1 values(1, 2, 'D')
insert into t1 values(1, 2, 'E')
insert into t1 values(2, 1, 'F')
insert into t1 values(2, 2, 'G')
insert into t1 values(2, 2, 'H')
insert into t2 values(10, 1, 'A')
insert into t2 values(10, 1, 'B')
insert into t2 values(10, 2, null)
insert into t2 values(20, 1, 'G')
insert into t2 values(20, 2, 'F')
insert into t2 values(20, 2, 'H')
insert into t2 values(20, 3, 'I')
insert into t2 values(20, 3, 'J')
My query result should be as follows...
cust1 cust2 zone pn_match_count total_unique_pn_count
1 10 1 2 3
1 10 2 0 4
1 20 1 0 4
1 20 2 1 5
1 20 3 0 2
2 10 1 0 3
2 10 2 0 2
2 20 1 0 2
2 20 2 1 3
2 20 3 0 2
I would really appreciate your help in writing this query.
Thanks in Advanceuser00 wrote:
No, that doesn't do it... I get no results with this query becuase the Cust_id in table 1 and table 2 are not the same.Yeah, I only realised that after I posted my query. I had interpreted pairs as "matching pairs" when what you meant was "permutations".
Cheers, APC
blog: http://radiofreetooting.blogspot.com -
SQL Query Help/ Converts seconds to day:hr:mi:se
I have query that returns value in seconds. How i will convert those seconds in DAY:HOUR:MIN:SEC in the same query? What will be the mathematical formulae or alogorithim for this?
Thanks
Munis Warsi
nullSeriously, you post 750+ lines of unformatted SQL statement and a completely unreadable and unformatted explain plan and you expect people to be able to help with that?
From what I can see it looks like some sort of query against an Oracle APPS database, and there are numerous calls to PL/SQL functions in there, so you're creating a multitude of context switches between the SQL and PL engines... that's known to cause performance problems.
Take a read of the discussions linked in the FAQ: Re: 3. How to improve the performance of my query? / My query is running slow.
And also consider if your question would be better asked in the Oracle Apps forum space instead. -
String filtering SQL Query help
We have a table set up as follows
| Type | Content | Date |
(date is unimportant for my problem, however)
I have a string which I am checking to see if it contains any of the words in the table with the type 'TEXT' using the following query.
SELECT content FROM content_blocking WHERE type = 'TEXT' and upper(?) like upper('%' || content || '%')
Basically this filter is returning words that it should not because they are contained within legitimate words. Basically I would like to filter all of the words with type 'ACCTEXT', which we have just added, out of the string before I check for the unallowed words of type 'TEXT'
I have been hacking away at getting a query that can do it, but for some reason can't put my finger on exactly how to do it. If anyone could help, it would be greatly appreciated.
Thanks,
MarshallThere is Oracle Text functionality which already does this. Check it out ...
SQL> CREATE TABLE codex_verbumum_prohibitorum (naughty_word varchar2(10))
2 /
Table created.
SQL> INSERT INTO codex_verbumum_prohibitorum VALUES ('GOSH')
2 /
1 row created.
SQL> INSERT INTO codex_verbumum_prohibitorum VALUES ('CRIPES')
2 /
1 row created.
SQL> INSERT INTO codex_verbumum_prohibitorum VALUES ('CRIVVENS')
2 /
1 row created.
SQL> INSERT INTO codex_verbumum_prohibitorum VALUES ('HECK')
2 /
1 row created.
SQL> INSERT INTO codex_verbumum_prohibitorum VALUES ('SEMEN')
2 /
SQL> CREATE TABLE what_ever (id number, some_text varchar2(100))
2 /
Table created.
SQL> INSERT INTO what_ever VALUES (1, 'Blah blah blah cripes blah')
2 /
1 row created.
SQL> INSERT INTO what_ever VALUES (2, 'Blah blah blah gosh blah')
2 /
1 row created.
SQL> INSERT INTO what_ever VALUES (3, 'Blah blah blah poop blah')
2 /
1 row created.
SQL> INSERT INTO what_ever VALUES (4, 'Blah heck blah cripes blah')
2 /
1 row created.
SQL> INSERT INTO what_ever VALUES (5, 'Blah advertisement blah')
2 /
1 row created.
SQL> COMMIT
2 /
Commit complete.
SQL> CREATE INDEX cvp_word ON codex_verbumum_prohibitorum (naughty_word)
2 INDEXTYPE IS CTXSYS.CTXRULE
3 /
Index created.
SQL>
SQL> SELECT w.id, cvp.naughty_word
2 FROM codex_verbumum_prohibitorum cvp, what_ever w
3 WHERE MATCHES(cvp.naughty_word, w.some_text)>0
4 /
ID NAUGHTY_WO
1 CRIPES
2 GOSH
4 CRIPES
4 HECK
SQL> You'll notice I have taken a flier at what I think is the naughty word in "advertisement" ;)
You may also be interested in an alternate Text implementation posted by Re: forbidden words list and intermedia index.
Cheers, APC
I see the forum nanny still thinks p00p is a dirty word :(
Message was edited by:
APC
Maybe you are looking for
-
Cannot update phone/add a new line after updating plan
I updated my data plan to a shared family plan and now would like to upgrade one of the phones and also add a new phone but can't - it says 'order still pending".How long do I need to wait?
-
How to install .SAR file
I just downloaded Netweaver Developer Studio SP 11. Its in .SAR format. Am wondering how to install it?
-
I'm new to Java and programming in general so forgive me. I need to get the ACL from a Lotus Notes database and convert it to a text file and so it can be used as an .htaccess file on our apache server. I know this is probably very simple, but I'm ha
-
Please support to remove the icloud account on my iphone
This is my story, i have a brother, he came to US 1 years ago, he go there to study, and after few months he bought an iphone 5 from a friend, and in the summer he came back to Viet Nam, and gave me that iphone, but i when i try to restore that iphon
-
Importing previously purchased content to new itunes
My compuer had a bug and they completely wiped out my hard drive. I reinstalled Itunes on my computer and it easily added all the music found on my computer, but all of the music I previously purchased on itunes was nowhere to be found. I thought "ch