Complicated query
I have a table that simplified can be explained this way:
Col1 Col2 Col3 Col4
aaaa data 200 2
aaaa data 180 2
aaaa data 160 2
aaaa data 130 2
aaaa data 125 2
aaaa data 100 2
bbbb data 400 3
bbbb data 295 3
bbbb data 170 3
bbbb data 160 3
cccc data 900 1
cccc data 200 1
cccc data 100 1
So, I have different categories of data. Category column is Col1.
Within category Col1, data is sorted according to Col3 Desc.
What I need to achieve is to select:
First 2 rows of aaaa
First 3 rows of bbbb
First 1 row of cccc
Please, note that the number of rows to be selected is in column Col4.
The result in this case would be:
Col1 Col2 Col3 Col4
aaaa data 200 2
aaaa data 180 2
bbbb data 400 3
bbbb data 295 3
bbbb data 170 3
cccc data 900 1
Thanks for your help.
P.S. My table is a Table Type and data is created by a function, so I have the possibility to manipulate through PL/SQL
/* Formatted on 4/8/2013 10:18:08 AM (QP5 v5.185.11230.41888) */
WITH t
AS (SELECT 'aaaa' col1, 200 col2, 2 col3 FROM DUAL
UNION ALL
SELECT 'aaaa' col1, 180, 2 FROM DUAL
UNION ALL
SELECT 'aaaa' col1, 160, 2 FROM DUAL
UNION ALL
SELECT 'aaaa' col1, 130, 2 FROM DUAL
UNION ALL
SELECT 'aaaa' col1, 125, 2 FROM DUAL
UNION ALL
SELECT 'aaaa' col1, 100, 2 FROM DUAL
UNION ALL
SELECT 'bbbb', 400, 3 FROM DUAL
UNION ALL
SELECT 'bbbb', 295, 3 FROM DUAL
UNION ALL
SELECT 'bbbb', 170, 3 FROM DUAL
UNION ALL
SELECT 'bbbb', 160, 3 FROM DUAL
UNION ALL
SELECT 'cccc', 900, 1 FROM DUAL
UNION ALL
SELECT 'cccc', 200, 1 FROM DUAL
UNION ALL
SELECT 'cccc', 100, 1 FROM DUAL),
t1
AS (SELECT t.*,
ROW_NUMBER () OVER (PARTITION BY col1 ORDER BY col2 DESC) rn
FROM t)
SELECT t1.col1,
'data' col2,
t1.col2 col3,
col3 col4
FROM t1
WHERE t1.rn <= t1.col3
COL1 COL2 COL3 COL4
aaaa data 200 2
aaaa data 180 2
bbbb data 400 3
bbbb data 295 3
bbbb data 170 3
cccc data 900 1
Similar Messages
-
Complicated Query Problem - Booking System
I am currently developing a hotel booking system for my University final year project and am having some serious problems with my queries to calculate room availability.
I felt the best method to calculate room availability was to first calculate which rooms were already booked for any specific queried dates and then to subtract those results from the list of total rooms. That would then return which rooms were available on those dates.
My first query successfully calculated which rooms were already booked using my test dates which were rooms 1,3 & 5. This result was stored in a temporary table. The second query then obtained the list of total rooms (1-10) and from this subtracted the results in the temporary table (1,3 & 5) which should have returned 2,4,6,7,8,9,10 as the rooms available. However, it returned the rather strange result "2,3,4,5,6,7,8,9,10,1,2,4,5,6,7,8,9,10,1,2,3,4,6,7,8,9,10"
It seems to take each result from the temporary table individually, subtract it from the total list of rooms, return the result and then move on to the next value in the temporary table. Which is why '1' is missing from the first 9 numbers, '3' from the second 9 and '5' from the last 9.
If anyone can help me solve this problem or suggest alternative methods I would be most appreciative.
Below is my MySQL code for the relevant parts of my database, the test values I am using and the two queries I am having problems with.
Advance Thanks!
CREATE TABLE booking
booking_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
e_mail VARCHAR(40),
arrival_date DATE NOT NULL,
departure_date DATE NOT NULL,
PRIMARY KEY(booking_id)
insert into booking (booking_id,e_mail,arrival_date,departure_date)
values ('[email protected]','2004-02-25','2004-02-28');
CREATE TABLE roombooked
booking_id INTEGER UNSIGNED NOT NULL REFERENCES booking(booking_id),
room_id INTEGER UNSIGNED NOT NULL REFERENCES rooms(room_no),
no_of_nights INTEGER UNSIGNED NOT NULL,
PRIMARY KEY(booking_id,room_id)
insert into roombooked(booking_id,room_id,no_of_nights)
values ('1','1','1'),('1','3','1'),('1','5','1');
CREATE TABLE rooms
room_no INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
room_name VARCHAR(11),
room_type VARCHAR(9),
single_price DECIMAL(5,2),
double_price DECIMAL(5,2),
PRIMARY KEY(room_no)
insert into rooms (room_name,room_type,single_price,double_price)
values ('shakespeare','principal','165','225'),
('keats','principal','165','225'),
('kipling','standard','125','165'),
('tennyson','superior','135','185'),
('shelley','deluxe','155','205'),
('brooke','superior','135','185'),
('wordsworth','deluxe','155','205'),
('milton','deluxe','155','205'),
('masefield','deluxe','155','205'),
('browning','deluxe','155','205');
FIRST QUERY
CREATE TEMPORARY TABLE roomsoccupied
SELECT roombooked.room_id FROM roombooked, booking
WHERE
roombooked.booking_id = booking.booking_id
AND
booking.arrival_date = '2004-02-25'
AND
booking.departure_date = '2004-02-28';
SECOND QUERY
SELECT rooms.room_no FROM rooms, roomsoccupied
WHERE
rooms.room_no != roomsoccupied.room_id;you haven't got a join in your second query
SECOND QUERY
SELECT rooms.room_no FROM rooms, roomsoccupied
WHERE
rooms.room_no != roomsoccupied.room_id;will return rubbish because you have created a valid view of your data with a sensible join.
try something like
SELECT rooms.room_no FROM rooms
WHERE rooms.room_no NOT IN (SELECT roomsoccupied.room_id FROM roomsoccupied);instead, which I believe should give you more meaningful data -
Hi. I have this query requirement:
public class Message implements Serializable {
private Long id;
private Subject sender;
private Subject receiver;
}btw Subject has a "name" and "id"
the query shall select the "other person" engaged in conversation with the current user.
it seems to be a simple query but, the problem arises when the conversation is engaged by the other one, not by the current user, and the query shall select both cases...
i just am not such an expert in EJBQL so can someone please help..<> mean not equals.
I have more experience with using plain Hibernate and Spring than using EJB 3.0. But I personally find EJB 3.0 to be orders of magnitude easier with almost no XML (except persistence.xml). I learnt to do in EJB, whatever I used to do with Spring + Hibernate in a couple of weeks. Today I can setup a development environment for a new project a lot faster with EJB 3.0 than with Spring + Hibernate. You may say it is just a one time activity, but still why go through the trouble when it can be avoided? :D
To me, a standard like EJB 3.0 is a boon because it lets me create highly portable and easily developed application archive, without having to worry about bundling a container, an ORM framework, a logging framework, a collections framework, a byte code manipulation framework, etc in my apps package.
Yes EJB 3.0 has its share of quirks, but then so do all frameworks and technologies! In this particular case, even Hibernate which is touted as the king of ORM frameworks, doesn't have a solution. -
A complicated query , group by issue (I guess)
Hi , on a bad structured database 10g running on Windows XP , I have two tables , one for the clients paid money and the other is for clients invoices , I need to calculate the sum of invoices of one client - which identified by his FirstNAme and LastName minus the sum of his paid money beside oney that already paid when making the invoice for example x buy an item , he made an invoice ith 100$ , he paid immediately 10$ nad then later - this will be on the other table - he paid 40$ , so my final result should be 50$ ,all in respect to the same year, here is what I did
SELECT NVL(SUM(NORMAL_CLIENTS.INV_VALUE), 0) - (NVL(SUM(NORMAL_CLIENTS.PAID), 0) + NVL(SUM(NORMAL_CLIENTS_RECEIPTS.REC_VALUE), 0))
AS EXPR1, NORMAL_CLIENTS.NAME, NORMAL_CLIENTS.SURNAME
FROM NORMAL_CLIENTS INNER JOIN
NORMAL_CLIENTS_RECEIPTS ON NORMAL_CLIENTS.NAME = NORMAL_CLIENTS_RECEIPTS.NAME AND
NORMAL_CLIENTS.SURNAME = NORMAL_CLIENTS_RECEIPTS.SURNAME
WHERE (TO_CHAR(NORMAL_CLIENTS.INV_DATE, 'YYYY') =
(SELECT DATE3
FROM TEMP)) AND (TO_CHAR(NORMAL_CLIENTS_RECEIPTS.REC_DATE, 'YYYY') =
(SELECT DATE3
FROM TEMP TEMP_1))
GROUP BY NORMAL_CLIENTS.NAME, NORMAL_CLIENTS.SURNAME
so this worked for me in one condition , the client has to have records on both table , otherwise it returns null
any help will be much appreciatedHi,
So that we can help you, can you provide us with some DDLs to create the tables, and some INSERTs to populate them with representative data?
You don't need to give the full structure of your tables, just relevant columns for the problem.
Also, to preserve formatting and readability, please use the tag to enclose code snippets.
Thanks. -
Can I stop a report from Re-executing the query when I go back to that page
I have a report that has a complicated query and looks at a lot of information to display the results. This query then links of to show details of individual items that were displayed in the result. But when I hit the back button on the browser, it executes the query again and it takes a while for the page to load.
Is there any way to stop this and only execute the query when the User pushes a Button on the page else display the previous results.
Thanks
SriramAnother alternative is to make that detail link open in a popup window using
javascript:popupURL(...);This way, the complicated report page is always visible. -
Why does the query work in SQL Developer, but not in APEX?
Hi, guys:
I have a silly question. I have a complicated query, and I tested it successfully with SQL developer, and result is correct. However, when I put it into APEX to generate a report, it always reports no data found. I also know the condition related to "other marks" select list in the where clause part causes this problem. It also looks strange: before I add this condition, everything works OK; after I add this condition, even I do not choose the "other marks" select list, other components do not work neither. I always got no data found result. Could anyone help me on this problem? You can also visit our developing site as http://lsg-solutions.com:8888/apex/f?p=206 to check the problem.
Thanks a lot
Sam
select distinct 'MAP','Detail',so.doc_number as "DOC Number", so.offender_id as "Offender ID", so.first_name||' '|| so.middle_name||' '||so.last_name as "Offender Name",
so.date_of_birth as "Date of Birth",
(select sc1.description from sor_code sc1 where sc1.code_id=so.race) as "Race",
(select sc2.description from sor_code sc2 where sc2.code_id=so.sex) as "Sex",
(select sc8.description from sor_code sc8 where sc8.code_id=so.hair_color) as "Hair Color",
(select sc9.description from sor_code sc9 where sc9.code_id=so.eye_color) as "Eye Color",
replace(replace(nvl2(sl.address1, sl.address1||' '||sl.address2 ||' '||sl.city ||' '||sl.county||' '||(select sc3.description from sor_code sc3 where sc3.code_id=sl.state)||' '||sl.zip, 'No Known Address'),'#'),',') as "Address",
replace(replace(nvl2(sl.physical_address1,sl.physical_address1||' '||sl.physical_city ||' '||sl.physical_county||' '||(select sc4.description from sor_code sc4 where sc4.code_id=sl.physical_state)||' '||sl.physical_zip, 'No Known Address'),'#'),',') as "Physical Address",
sl.status as "Status",
sl.jurisdiction as "Jurisdiction",
to_char(sl.ADDRESS_LATITUDE) as "Address Latitude",to_char(sl.address_longitude) as "Address Longitude",
to_char(sl.physical_address_latitude) as "Physical Latitude",to_char(sl.physical_address_Longitude) as "Physical Longitude",
decode(rox.habitual, 'Y', 'Habitual', '') as "Habitual",
decode(rox.aggravated, 'Y', 'Aggravated', '') as "Aggravated",
rox.status as "Registration Status",
rox.registration_date as "Registration Date",
rox.end_registration_date as "End Registration Date"
from sor_location sl, sor_offender so, registration_offender_xref rox, sor_last_locn_v sllv
where rox.offender_id=so.offender_id
and sllv.offender_id(+)=so.offender_id
and sl.location_id(+)=sllv.location_id
and rox.status not in ('Merged')
and rox.reg_type_id=1
and upper(rox.status)='ACTIVE'
and nvl(rox.admin_validated, to_date(1,'J'))>=nvl(rox.entry_date, to_date(1,'J'))
and (((select sc11.description from sor_code sc11 where sc11.code_id=so.race and sc11.description=:P5_SL_RACE) is not null ) or (:P5_SL_RACE is null))
and (((select sc12.description from sor_code sc12 where sc12.code_id=so.sex and sc12.description=:P5_SL_SEX) is not null ) or (:P5_SL_SEX is null))
and (((select sc13.description from sor_code sc13 where sc13.code_id=so.hair_color and sc13.description=:P5_SL_HAIR_COLOR) is not null ) or (:P5_SL_HAIR_COLOR is null))
and (((select sc14.description from sor_code sc14 where sc14.code_id=so.eye_color and sc14.description=:P5_SL_EYE_COLOR) is not null ) or (:P5_SL_EYE_COLOR is null))
and (( so.offender_id in(select sm.offender_id from sor_code sc15, sor_mark sm, sor_offender so1 where sm.offender_id=so1.offender_id and sc15.code_id=sm.code and sc15.description=:P5_SL_OTHER_MARKS and sm.description is not null)) or (:P5_SL_OTHER_MARKS is null))My suggestion would be to put some instrumentation into your query and see what values you are using.. Or even simpler take out ALL the where clauses you can until data starts to sho wup and then add them back in one at a time until you find the culprit..
My bet would be on any date comparisons you are doing between page items and database columns..
Thank you,
Tony Miller
Dallas, TX -
Sql query ..need idea to write complex query
Hi there,
I have assigned the task to write a sql query to get the output as the below stored proc does.
In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
Is anyone could help me?
Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
create or replace PROCEDURE vpp_station_summary_report (
in_user_id IN VARCHAR2,
in_report_id IN NUMBER,
in_time_from IN vppstation.avi_status_history.status_eff_date%TYPE,
in_time_to IN vppstation.avi_status_history.status_eff_date%TYPE,
result OUT SYS_REFCURSOR)
AS
CURSOR station_loop IS
SELECT ash.station_id,
ash.avi_id,
ash.state_id,
ash.state_eff_date
FROM vppstation.avi_state_history ash
JOIN vpproadside.vpp_report_stations
ON vpp_report_stations.station_id = ash.station_id
AND vpp_report_stations.vpp_report_seq_number = in_report_id
WHERE ash.state_eff_date BETWEEN in_time_from AND in_time_to
ORDER BY ash.station_id,
ash.avi_id,
ash.state_eff_date,
ash.ash_id;
-- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
-- in_time_from
CURSOR entry_state (
state_station_id vppstation.avi_state_history.station_id%TYPE,
state_avi_id vppstation.avi_state_history.avi_id%TYPE,
state_state_date vppstation.avi_state_history.state_eff_date%TYPE
IS
SELECT ash.state_id
FROM vppstation.avi_state_history ash
WHERE ash.station_id = state_station_id
AND ash.avi_id = state_avi_id
AND ash.state_eff_date < state_state_date
ORDER BY ash.state_eff_date DESC,
ash.ash_id DESC;
current_station_id vppstation.avi_state_history.station_id%TYPE;
current_avi_id vppstation.avi_state_history.avi_id%TYPE;
current_state_id vppstation.avi_state_history.state_id%TYPE;
current_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
period_length NUMBER;
next_station_id vppstation.avi_state_history.station_id%TYPE;
next_avi_id vppstation.avi_state_history.avi_id%TYPE;
next_state_id vppstation.avi_state_history.state_id%TYPE;
next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
station_open_total NUMBER;
station_closed_total NUMBER;
station_all_report_total NUMBER;
current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
state_open vppstation.avi_control_state_code.state_id%TYPE;
state_closed vppstation.avi_control_state_code.state_id%TYPE;
state_all_report vppstation.avi_control_state_code.state_id%TYPE;
BEGIN
SELECT state_id
INTO state_open
FROM vppstation.avi_control_state_code
WHERE state_type = 'E'
AND state_active_ind = 'A';
SELECT state_id
INTO state_closed
FROM vppstation.avi_control_state_code
WHERE state_type = 'D'
AND state_active_ind = 'A';
SELECT state_id
INTO state_all_report
FROM vppstation.avi_control_state_code
WHERE state_type = 'S'
AND state_active_ind = 'A';
current_station_id := -1;
current_avi_id := -1;
current_state_id := state_closed;
current_state_eff_date := in_time_from;
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
-- for starters - ensure that there is report data for all requested stations...
INSERT INTO vpproadside.vpp_station_summary
vpp_report_seq_number,
station_id,
station_name,
ln_number,
lane_name,
station_open,
station_close,
station_all_report,
station_total
SELECT in_report_id,
vrs.station_id,
si.station_name,
l.ln_number,
l.lane_name,
0.0,
0.0,
0.0,
0.0
FROM vpproadside.vpp_report_stations vrs
LEFT OUTER JOIN vpproadside.stations_installed si
ON si.station_id = vrs.station_id
LEFT OUTER JOIN vppstation.lane_name l
ON l.station_id = vrs.station_id
WHERE vrs.vpp_report_seq_number = in_report_id;
-- loop over state history and update information for all stations found
OPEN station_loop;
LOOP
FETCH station_loop
INTO
next_station_id,
next_avi_id,
next_state_id,
next_state_eff_date;
IF station_loop%NOTFOUND THEN
next_station_id := -1;
next_avi_id := -1;
END IF;
-- if station/avi has changed take the end of the report period
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
period_length := in_time_to - current_state_eff_date;
ELSE
-- otherwise the start of the next period marks the end of the current period
period_length := next_state_eff_date - current_state_eff_date;
END IF;
-- if we have a real station id then do some work...
IF (current_station_id <> -1) THEN
-- determine which category the period fits to and apply calculation
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length - 1;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length - 1;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length - 1;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
-- if the station/avi has changed then commit changes to db
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
UPDATE vpproadside.vpp_station_summary
SET
station_open = station_open_total,
station_close = station_closed_total,
station_all_report = station_all_report_total
WHERE vpp_report_seq_number = in_report_id
AND station_id = current_station_id
AND ln_number = current_avi_id;
-- reset counts
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
END IF;
END IF;
-- if we got past the last record then stop processing
EXIT WHEN station_loop%NOTFOUND;
-- if the station/avi is changing, get the state that was 'current' at in_time_from
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
current_state_eff_date := in_time_from;
OPEN entry_state (
next_station_id,
next_avi_id,
in_time_from
FETCH entry_state
INTO current_state_id;
IF entry_state%NOTFOUND THEN
current_state_id := state_closed;
END IF;
CLOSE entry_state;
period_length := next_state_eff_date - current_state_eff_date;
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
END IF;
current_state_id := next_state_id;
current_state_eff_date := next_state_eff_date;
current_station_id := next_station_id;
current_avi_id := next_avi_id;
END LOOP;
CLOSE station_loop;
-- update the totals for the percentage calculation
UPDATE vpproadside.vpp_station_summary
SET
station_total = station_open + station_close+ station_all_report
WHERE vpp_report_seq_number = in_report_id;
-- 'fix' the totals that are still zero to avoid divide by zero errors...
-- note: all the percentages will still come out as zero since the total
-- was zero
UPDATE vpproadside.vpp_station_summary
SET
station_total = 1.0
WHERE vpp_report_seq_number = in_report_id
AND station_total = 0.0;
OPEN result FOR
SELECT station_name "Site Name",
lane_name "Lane Name",
TO_CHAR((station_open / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
TO_CHAR((station_close / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id
ORDER BY UPPER(station_name),
UPPER(lane_name);
DELETE FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id;
END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
Edited by: Indhu Ram on Mar 10, 2010 11:12 AMExactly dont know what you are asking for but I can suggest you some tips here
- If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
FROM table1, table2
WHERE
<some conditions>
- If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
something like this
SELECT function_name(parameter1, parameter2....) from dual
Hope this will help -
Mysql query returns different number of records from coldfusion and navicat
Hi
I'm hoping that someone can suggest a basic strategy to debug this.
I have a fairly large and complicated query that is executed by a function in a cfc.
It returns (for example) 100 rows.
If I use cfdump and then copy and paste the SQL of the query (with the variables, of course) into Navicat and execute exactly the same query on the same mySQL database, it returns 130 rows.
Same SQL string, same database, same data - the only difference is that in one instance Navicat submits the query and in the other, Coldfusion does.
Has anyone ever had anything like this happen before?Ok I found my own bug. Of *course* the sql queries were not identical.. they could not possibly have been. My mistake was thinking that they were.
The problem was part of the WHERE clause:
AND orderid in (500,503,505)
In the coldfusion code this was
AND orderid in (<cfqueryparam cfsqltype="cf_sql_varchar" value="#lstOrderID#">)
which of course rendered in mySQL as AND orderid in ('500,503,505')
This was not immediately apparent as the cfdump returns this as AND orderid in (?) with the variable in the array below. -
Local Calculation (Summation) in query doesn't display correctly in web
Hi All,
I have been working on a complicated query where I have formulas that perform calculations. I then Hide these formulas and use them in another formula for further calculations. The new calculations I then use local summation to basically just add the columns values and come up with an overall result. Works perfect and is displayed perfectly.
Problem is now in the web. Either using a Pie Chart or just simply an Analysis item, the values are not displayed correctly at all. The Pie Chart only displays the first row of data (not the overall result...which is a local summation...which is what I would prefer) and suprised that the Analysis item doesn't basically display what the query does. I'm guessing it has to do with this local calculation.
Can someone explain this behavior?
Thanks.Anyone any ideas?
-
Reusing query results in PL/SQL
I have a procedure in a package that I want to query several times using the analytical function row_number to get, say, the 5th row and the 95th row:
select days_missed_negative_is_late
into l_5pct
from (select days_missed_negative_is_late,
row_number() over(order by days_missed_negative_is_late asc) rn
from (*some complicated query*)
order by days_missed_negative_is_late))
where rn = 5;
then I do the whole thing again, except the last line reads "rn=95". This seems inefficient. I would like to build the results one time then query it twice:
select days_missed_negative_is_late
into l_5pct
from something
where rn = 5;
select days_missed_negative_is_late
into l_5pct
from something
where rn = 95;
or the equivalent functionality, of course. Again, this is in a PL/SQL package. Any ideas of the best way to build the results and read them several times?Here is an example.
1 select object_name from
2 (select object_name,row_number() over(order by created) rn
3 from all_objects
4 where rownum<101)
5* where rn in(5,95)
SQL> /
OBJECT_NAME
I_CON2
DEPENDENCY$
You could for example 1) use a cursor and loop or
2) select and bulk collect.
I hope this helps. -
I am dealing with an issue that I believe I have boiled it down to being a Forms issue. One of my developers has a form that is taking 40+ minutes to run a pretty complicated query. At first I believed that it was a query or development issue, however the same query can be ran from Toad or from SQLPlus in under a few seconds. I have even ran the query from SQLPlus on the forms server with the same speedy performance. The only environment in which this query takes almost an hour to run is if it is ran from her .FMX ... I am soooooo at a loss right now as to what I could do to fix this. Has anyone experienced something of this nature?
Additionally the query returns ZERO results and this is an expected outcome so I don't believe it has to do with Toad buffering or SQLPlus return the rows as they are fetched. Anyway I'm at a loss and any help what-so-ever will be greatly appreciated.To show what can go wrong look at this simple example.
HR@> CREATE TABLE a (ID VARCHAR2(10) PRIMARY KEY);
Table created.
HR@>
HR@> insert into a select rownum from dual connect by rownum <= 1e6;
1000000 rows created.
HR@>
HR@> set timing on
HR@>
HR@> select * from a where id = 100;
ID
100
Elapsed: 00:00:00.34
HR@>
HR@> select * from a where id = '100';
ID
100
Elapsed: 00:00:00.00
HR@> explain plan for
2* select * from a where id = 100
HR@>
HR@> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 2248738933
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 7 | 522 (12)| 00:00:07 |
|* 1 | TABLE ACCESS FULL| A | 1 | 7 | 522 (12)| 00:00:07 |
Predicate Information (identified by operation id):
PLAN_TABLE_OUTPUT
1 - filter(TO_NUMBER("ID")=100)Because of implicit conversion (as explain plan shows) select * from a where id = 100 takes longer than select * from a where id = '100'. -
Select query or RH_READ_INFTY?
Hello experts,
I have a report where I am fetching the Work schedule(IT 0007) for all employees for all the period. I have written a select query for the same. I am planning to replace it with FM RH_READ_INFTY. Since I am not using LDB, I cannot use Macros to read data.
I ran a trace using both to find performances of both, but couldnt actually figure out as it doesnt show the time taken by FM. Instead it shows select queries fired on PA0007 table(which I am doing in first place).
So please guide me as to which approach I should follow in this or any general case when it comes to reading IT data without using LDB.
Thanx!,
HOward.Hello Marcin,
Thankyou for your valuable response.
I guess you would be calling this fm for each EE separately
Yes. I am looping on all PERNRs and have to fetch data for around 4-6 infotypes for each employee.
So I guess I will have to use this FM 4-6 times for each employee. Even with the FM, it must opening a database connection.
I feel, it would be as bad as firing select queries inside a loop.
The custom select can be optimzed to establish the communication
with DB only once for whole population (which of course means more complicated
query to analyze by DB Optimizer but the data would be transported in one run).
As you said,
What I have done is, fired queries on all PA tables for respective infotypes and fetched the all the data in one shot.
Later I have used READ statement to get the data I want.
It really depends on your requirement. If you go for custom select query,
you just extract specific information from the system skipping all the authorization checks,
That might be a crucial issue. What are the authorization checks here we are talking about?
Does the FM read data from any
other tables than we do in select queries?
Thnx!
Howard -
Hello All --
We use the below Query and would like to change the BT Address to show just the address -- not the City, State, Zip and Country. Help?! Thanks -- Mike
SELECT 'Invoice' "Invoice/AR CM", T0.CardCode
"BP Code", T0.CardName 'Company',
T0.Address 'BT Address', T2.City 'BT City', T2.State1 'BT State', T2.ZipCode 'BT Zip',
T2.Phone1 'BT Phone', T0.Address2 'ST Address',
T3.Name, T0.DocDate,T0.DocNum,
T0.DocTotal 'Gross Amt', T0.TotalExpns 'Freight/Svc Charge',
(T0.DocTotal - T0.VatSum-T0.TotalExpns) 'Net Order',
T1.SlpName 'Sales Rep',
T1.Commission '% Commision',
((T0.DocTotal - T0.VatSum-T0.TotalExpns)*(T1.Commission/100))
'Commission Amount', T4.GroupName 'Group'
FROM dbo.OINV T0 LEFT JOIN dbo.OSLP T1 ON T0.SlpCode = T1.SlpCode
LEFT JOIN dbo.OCRD T2 ON T0.CardCode = T2.CardCode
LEFT JOIN dbo.OCPR T3 ON T0.CntctCode = T3.CntctCode
LEFT JOIN dbo.OCRG T4 ON T4.GroupCode = T2.GroupCode
WHERE (T1.SlpName BETWEEN '[%0]' and '[%1]') AND
(T0.DocDate BETWEEN '[%2]' AND '[%3]')
UNION ALL
SELECT 'Credit Memo' "Credit", T0.CardCode, T0.CardName,
T0.Address, T2.City, T2.State1, T2.ZipCode, T2.Phone1,T0.Address2,
T3.Name, T0.DocDate,T0.DocNum,
-T0.DocTotal, -T0.TotalExpns,
-(T0.DocTotal - T0.VatSum-T0.TotalExpns),
T1.SlpName,
T1.Commission,
((T0.DocTotal - T0.VatSum-T0.TotalExpns)*(-T1.Commission/100)),
T4.GroupName 'Group'
FROM dbo.ORIN T0 LEFT JOIN dbo.OSLP T1 ON T0.SlpCode = T1.SlpCode
LEFT JOIN dbo.OCRD T2 ON T0.CardCode = T2.CardCode
LEFT JOIN dbo.OCPR T3 ON T0.CntctCode = T3.CntctCode
LEFT JOIN dbo.OCRG T4 ON T4.GroupCode = T2.GroupCode
WHERE (T1.SlpName BETWEEN '[%0]' and '[%1]') AND
(T0.DocDate BETWEEN '[%2]' AND '[%3]')Hi Mike,
you wrote or use such a complicated query, but u re not able to change a easy select? U should understand what u are doing there!
Well, here we go, i tried this query and it works :
SELECT 'Invoice' "Invoice/AR CM", T0.CardCode
"BP Code", T0.CardName 'Company',
T0.Address 'BT Address',
T2.Phone1 'BT Phone', T0.Address2 'ST Address',
T3.Name, T0.DocDate,T0.DocNum,
T0.DocTotal 'Gross Amt', T0.TotalExpns 'Freight/Svc Charge',
(T0.DocTotal - T0.VatSum-T0.TotalExpns) 'Net Order',
T1.SlpName 'Sales Rep',
T1.Commission '% Commision',
((T0.DocTotal - T0.VatSum-T0.TotalExpns)*(T1.Commission/100))
'Commission Amount', T4.GroupName 'Group'
FROM dbo.OINV T0 LEFT JOIN dbo.OSLP T1 ON T0.SlpCode = T1.SlpCode
LEFT JOIN dbo.OCRD T2 ON T0.CardCode = T2.CardCode
LEFT JOIN dbo.OCPR T3 ON T0.CntctCode = T3.CntctCode
LEFT JOIN dbo.OCRG T4 ON T4.GroupCode = T2.GroupCode
WHERE (T1.SlpName BETWEEN '%0' and '%1') AND
(T0.DocDate BETWEEN '%2' AND '%3')
UNION ALL
SELECT 'Credit Memo' "Credit", T0.CardCode, T0.CardName,
T0.Address, T2.Phone1,T0.Address2,
T3.Name, T0.DocDate,T0.DocNum,
-T0.DocTotal, -T0.TotalExpns,
-(T0.DocTotal - T0.VatSum-T0.TotalExpns),
T1.SlpName,
T1.Commission,
((T0.DocTotal - T0.VatSum-T0.TotalExpns)*(-T1.Commission/100)),
T4.GroupName 'Group'
FROM dbo.ORIN T0 LEFT JOIN dbo.OSLP T1 ON T0.SlpCode = T1.SlpCode
LEFT JOIN dbo.OCRD T2 ON T0.CardCode = T2.CardCode
LEFT JOIN dbo.OCPR T3 ON T0.CntctCode = T3.CntctCode
LEFT JOIN dbo.OCRG T4 ON T4.GroupCode = T2.GroupCode
WHERE (T1.SlpName BETWEEN '%0' and '%1') AND
(T0.DocDate BETWEEN '%2' AND '%3')
regards -
Query contain inner join to external DB
Hi every body,
I have created a new sql query that contain inner join to external db of the production software. The query also uses parameters for filter data by date .
I succeeded to create a qurey that will work including inner join to the external DB and parameters,
Here is the query:
SELECT T0.DocNum, T0.DocDate, T0.CardCode, T0.CardName, T1.ItemCode, T1.Dscription, T1.Quantity, T1.TotalSumSy, T1.LineTotal, T0.Canceled, T2.Family
FROM [XXX].dbo.AllItems T2
RIGHT OUTER JOIN INV1 T1 ON T1.ItemCode= T2.ItemPN collate SQL_Latin1_General_CP1_CI_AS
INNER JOIN OINV T0 ON T1.DocEntry = T0.DocEntry
INNER JOIN OITM T3 ON T1.ItemCode = T3.ItemCode
INNER JOIN OITB T4 ON T3.ItmsGrpCod = T4.ItmsGrpCod
INNER JOIN OCRD T5 ON T0.CardCode = T5.CardCode
INNER JOIN OACT T6 ON T1.AcctCode = T6.AcctCode
Where T0.DocDate BETWEEN [%0] AND [%1]
but when I add a union statement the query does not work again.
If I remove the parameters every thing is working fine.
what is the problem with my query?
Thank you all very much.SBO does not manage correctly variables in complicated query. There is a note about it:
Note 730960 - SAP Business One does not identify variables in long queries
https://websmp130.sap-ag.de/sap/bc/bsp/spn/sapnotes/index2.htm?numm=730960
This note describe the method to get the parameters in variables and their usage. -
Query Generator Error-Clarification required
Hai Experts,
I wrote a query select * from OPOR where Docnum>'[%0]
This works all fine.
When I replace the OPOR table name with a view name created for the table OPOR, the same statement does not work and returns error incorrect syntax.
Pls explain why does this happen?
Thanks
AnandDear Gordon,
Thanks for your response. The following is the query I wrote in Query Generator, when I give a literal value, the query worked without any error. When I use dynamic user input string, it returns errror. In this case the database object IR is a view, that I created to facilitate a complicated query.
I need that, user should be able to input his criteria value. Please help me to achieve this.
Thanks in advance.
Regards
Anand
SELECT distinct t0.PO,max(t0.Supplier) Supplier,max(t0.OrderNo) OrderNo,max(t0.StyleNo) StyleNo,Max(t0.Process) Process,Max(t0.Date) IssueDate,
(select isnull(sum(t1.Quantity),0) from IR t1 where t1.PO=t0.PO and t1.Ttype<0) TotalIssued,
(select isnull(sum(t2.Quantity),0) from IR t2 where t2.po=t0.po and t2.Ttype>0) TotalReceived,
isnull((select sum(t1.Quantity) from IR t1 where t1.PO=t0.PO and t1.Ttype<0),0)-
isnull((select sum(t2.Quantity) from IR t2 where t2.po=t0.po and t2.Ttype>0),0) Balance from ir t0 where
t0.Process='[%1]'
and isnull((select sum(t1.Quantity) from IR t1 where t1.PO=t0.PO and t1.Ttype<0),0)>0
Group By t0.po
Maybe you are looking for
-
Exception error while running the page? help me please
Error Page Exception Details. oracle.apps.fnd.framework.OAException: oracle.jbo.SQLStmtException: JBO-27122: SQL error during statement preparation. Statement: SELECT * FROM (select opi.invoice_num ,opi.purchase_orders ,op.payment_num ,opi.amount_pai
-
When downloading from library using ADE and transferring to my kobo touch I get the above error message on my Mac computer. Can anyone help me figure this out?
-
How do I confirm ITS flow logic exists?
Hi Guys, We are upgrading from R/3 4.6C to ECC6.0. The old ITS 2 applications one on ITS 6.2 and another ITS 2.0. We are having difficulty in finding out/confirming if there is a ITS flow logic involved in the stand alone ITS. This will tell us what
-
NIC ROUTER requirement for 10g RAC database
I need to know what hardware to order in setting up an 10g RAC database without a single-point-of-failure. My question centers on the networks. If each server has one NIC for the public interface and one NIC for the private interconnect, aren't the r
-
Closed Captioning Functionality in Premier Pro CS3?
Hello again everyone! I am new to the Closed Captioning arena and I'm assessing my options to go about cc'ing my clips. I'm working with CS3 Pro, but I'm not familiar with all of the software in the bundle. Is there anything specific for this? Thank