Table joining query with dates
Hello,
I have two tables, one containing a list of pupils, their class start date and their class end dates. The second table contains the address (postcode) history of the pupil. I need to bring these two tables together into one query to show all the classes from the 'pupils' table and add in the most recent postcode of the address prior to the start date of the clasS from the 'addresses' table. I.e. to show where the pupil lived when they started the class.
Could anyone show me how to do this please? I've provided a 'desired' table to show what I need the results to look like.
I hope this is clear, please ask if it isn't - I'm sure this should be simple! But I can't get my head around it. I'm using Oracle 9i and SQL Developer.
Thanks :)
select pupils.* from
(select 'A227' as pupil_id, to_date('21/04/2010','dd/mm/rrrr') class_start, to_date('21/09/2010','dd/mm/rrrr') class_end from dual union all
select 'A227' as pupil_id, to_date('08/08/2011','dd/mm/rrrr'), to_date('26/10/2011','dd/mm/rrrr') from dual ) pupils
select addresses.* from
(select 'A227' as pupil_id, to_date('20/04/2010','dd/mm/rrrr') address_start, null address_end, 'TW1 XVT' as postcode from dual union all
select 'A227' as pupil_id, to_date('03/08/2011','dd/mm/rrrr'), to_date('31/10/2011','dd/mm/rrrr'), 'TW3 ZE3' as postcode from dual union all
select 'A227' as pupil_id, to_date('01/11/2011','dd/mm/rrrr'), null, 'n23 4ty' as postcode from dual) addresses
select desired.* from
(select 'A227' as pupil_id, to_date('21/04/2010','dd/mm/rrrr') class_start, to_date('21/09/2010','dd/mm/rrrr') class_end, to_date('20/04/2011','dd/mm/rrrr') as address_start, 'TW1 XVT' as postcode from dual union all
select 'A227' as pupil_id, to_date('08/08/2011','dd/mm/rrrr') class_start, to_date('26/10/2011','dd/mm/rrrr') class_end, to_date('03/08/2011','dd/mm/rrrr') as address_start, 'TW3 ZE3' as postcode from dual) desired
Hi,
That's an example of a Top-N Query , and here's one way to do it:
WITH got_r_num AS
SELECT p.*
, a.address_start
, a.postcode
, ROW_NUMBER () OVER ( PARTITION BY p.pupil_id
, p.class_start
ORDER BY a.address_start DESC
) AS r_num
FROM pupils p
JOIN addresses a ON p.pupil_id = a.pupil_id
AND p.class_start >= a.address_start
SELECT pupil_id, class_start, class_end, address_start, postcode
FROM got_r_num
WHERE r_num = 1
;As you can see, the sib-query pairs each pupil and class with all the earlier addresses, and then numbers the addresses such that the latest address_start gets the lowest r_num (that is, 1, since ROW_NUMBER always starts with 1). The main query displays only the most recent address (the one with r_num = 1) for each pupil and class.
Does addresses.address_end plays any role in this problem? For example, would it matter if the most recent address for a given pupil and class had expired before the class started? That is, if we change the middle of address to:
select 'A227' as pupil_id
, to_date ('03/08/2011', 'dd/mm/rrrr')
, to_date ('07/08/2011', 'dd/mm/rrrr') -- Not 31/10/2011
, 'TW3 ZE3' as postcode
from dual would it still count as the last address before the class that started on 08/08/2011?
Edited by: Frank Kulash on Nov 1, 2011 11:36 AM
Added question about address_end
Similar Messages
-
How to compare result from sql query with data writen in html input tag?
how to compare result
from sql query with data
writen in html input tag?
I need to compare
user and password in html form
with all user and password in database
how to do this?
or put the resulr from sql query
in array
please help me?Hi dejani
first get the user name and password enter by the user
using
String sUsername=request.getParameter("name of the textfield");
String sPassword=request.getParameter("name of the textfield");
after executeQuery() statement
int exist=0;
while(rs.next())
String sUserId= rs.getString("username");
String sPass_wd= rs.getString("password");
if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
exist=1;
if(exist==1)
out.println("user exist");
else
out.println("not exist"); -
How to build table join query in Jdeveloper
Hi,
Can someone tell me how to build table join query in Jdeveloper's Expression Builder UI?[Is it possible to create a table of contents in Crystal Reports?|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_erq/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233313335333133303330%7D.do]
-
Left join query with join of three tables
I'm trying to build a query which has me stumped. Most of the query is fairly straightforward but I've run into an issue I'm not sure how to solve.
Background:
We have actions stored in i_action.
We have the available attributes for each type of action. The available attributes for each action are described in shared_action_attribute. Each type of action may have up to three attributes or none at all.
We have the values stored for the attributes in i_attribute_value.
A written example:
We have a transfer action (action_code B4). The entry of the B4 action into i_action records the fact that the transfer occurred and the date on which it occurred. The available attributes for a transfer action are the receiving function code, the receiving unit number, and the transfer reason code. These available attribute types and their order are stored in shared_action_attribute. The actual values of the attributes for a specific transfer action are stored in i_attribute_value.
Now i_action and i_attribute_value can be directly linked through action_seq in i_action and ia_action_seq in i_attribute_value. A left join built between these two tables provides results for all actions (including actions which have no attributes) and attribute values (see query 1 below).
There are two issues. First, I only want the first two attributes. In order to specify the first two attributes, I also have to link i_attribute_value to shared_action_attribute (which is where the order is stored). I can build a simple query (without the left join) linking the three tables but then actions with no attributes would be excluded from my result set (see query 2 below).
The second issue is that I would actually like one row returned for each action with first_attribute and second_attribute as columns instead of two rows.
The final query will be used to create a materialized view.
Here are the tables and examples of what's stored in them:
TABLE i_action
Name Type
ACTION_SEQ NUMBER(10)
ACTION_DATE DATE
ACTION_CODE VARCHAR2(3)
DELETED VARCHAR2(1)
EXAMPLE ROWS
ACTION_SEQ ACTION_DATE ACTION_CODE DELETED
45765668 09-OCT-09 B2 A
45765670 09-OCT-09 BA A
45765672 09-OCT-09 B6 A
45765673 09-OCT-09 B4 A
45765674 09-OCT-09 G1 A
45765675 09-OCT-09 M3 A
TABLE i_attribute_value
Name Type
IA_ACTION_SEQ NUMBER(10)
SACTATT_SACT_CODE VARCHAR2(3)
SACTATT_SAT_TYPE VARCHAR2(3)
VALUE VARCHAR2(50)
EXAMPLE ROWS
IA_ACTION_SEQ SACTATT_SACT_CODE SACTATT_SAT_TYPE VALUE
45765668 B2 ACO 37B
45765670 BA ROA D
45765670 BA ROR P
45765672 B6 CAT C
45765673 B4 RFC E
45765673 B4 TRC P
45765673 B4 RUN 7
45765674 G1 SS 23567
45765674 G1 ASG W
TABLE shared_action_attribute
Name Type
SACT_CODE VARCHAR2(3)
SAT_TYPE VARCHAR2(3)
ORDER NUMBER(2)
TITLE VARCHAR2(60)
EXAMPLE ROWS
SACT_CODE SAT_TYPE ORDER TITLE
B2 ACO 1 Office code
BA ROR 1 Reason for reopen
BA ROA 2 Reopen authority
B6 CAT 1 Category
B4 RFC 1 Receiving function code
B4 RUN 2 Receiving unit code
B4 TRC 3 Transfer reason code
G1 SS 1 Staff sequence
G1 ASG 2 Assignment reason
QUERY 1:
This is my current query along with its results. Most of it is straightforward select but one column is populated using the last_value analytical function (thanks to you guys). The last column in the below view stores the attribute value. What I want is to replace that single column with two columns named first_attribute and second_attribute and to eliminate any other attributes.
SELECT ia.action_seq, ia.action_date, ia.action_code cod,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
AND iav.sactatt_sat_type = 'SS'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
value
FROM i_action ia LEFT JOIN i_attribute_value iav
ON iav.ia_action_seq = ia.action_seq
WHERE ia.deleted = 'A';
ACTION_SEQ ACTION_DA COD STAFF_SEQ VALUE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 P
45765673 09-OCT-09 B4 67089 7
45765674 09-OCT-09 G1 23567 23567
45765674 09-OCT-09 G1 23567 W
45765675 09-OCT-09 M3 23567
QUERY 2:
This query limits to the first two attributes but it also drops actions which have no attributes and it still creates multiple rows for each action instead of a single row with two columns for the attributes.
SELECT ia.action_seq, ia.action_date, ia.action_code cod,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
AND iav.sactatt_sat_type = 'SS'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
value
FROM shared_action_attribute saa, ims_action ia, ims_attribute_value iav
WHERE iav.ia_action_seq = ia.action_seq
AND iav.sactatt_sact_code = saa.sact_code
AND iav.sactatt_sat_type = saa.sat_type
AND saa.display_order IN ('1','2')
AND ia.deleted = 'A';
ACTION_SEQ ACTION_DA COD VALUE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 7
45765674 09-OCT-09 G1 23567 23567
45765674 09-OCT-09 G1 23567 W
I found this pretty complex to try to write out - I hope I've been clear.
Thanks so much!Ok, here's more information with a simplified question. I figured out the syntax for building my query with the three tables. My final query returns multiple rows (multiple attributes per action). Instead of multiple rows, I'd like two columns (first_attribute, and second_attribute) in a single row (I only need the first two attributes).
Here's the action table:
CREATE TABLE I_ACTION
ACTION_SEQ NUMBER(10) NOT NULL,
ACTION_DATE DATE,
ACTION_CODE VARCHAR2(3 BYTE) NOT NULL,
DELETED VARCHAR2(1 BYTE),
);With the following rows added:
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765668, '09-oct-2009', 'B2', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765670, '09-oct-2009', 'BA', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765672, '09-oct-2009', 'B6', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765673, '09-oct-2009', 'B4', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765674, '09-oct-2009', 'G1', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765675, '09-oct-2009', 'M3', 'A');
COMMIT;The attribute table is:
CREATE TABLE I_ATTRIBUTE_VALUE
IA_ACTION_SEQ NUMBER(10) NOT NULL,
SACTATT_SACT_CODE VARCHAR2(3 BYTE) NOT NULL,
SACTATT_SAT_TYPE VARCHAR2(3 BYTE) NOT NULL,
VALUE VARCHAR2(50 BYTE),
);With the following rows:
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765668, 'B2', 'ACO', '37B');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765670, 'BA', 'ROR', 'P');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765670, 'BA', 'ROA', 'D');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765672, 'B6', 'CAT', 'C');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'RFC', 'E');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'RUN', '7');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'TRC', 'P');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765674, 'G1', 'SS', '23567');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765674, 'G1', 'ASG', 'W');
COMMIT;And finally, the shared table:
CREATE TABLE SHARED_ACTION_ATTRIBUTE
SACT_CODE VARCHAR2(3 BYTE) NOT NULL,
SAT_TYPE VARCHAR2(3 BYTE) NOT NULL,
TITLE VARCHAR2(25 BYTE) NOT NULL,
DISPLAY_ORDER NUMBER(2) NOT NULL
);With the following rows:
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'RFC', 'Y', 'Rcv. Function Code', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'CAT', 'Y', 'Category', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('G1', 'SS', 'Y', 'Staff Name', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B2', 'ACO', 'Y', '"Other" Office Code', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'RUN', 'Y', 'Receiving Unit Number', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'LEP', 'N', 'LEP Issue/Sub Category', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'TRC', 'Y', 'Transfer Reason Code', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'NEP', 'N', 'NEP Issue', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('G1', 'ASG', 'Y', 'Assignment Reason', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B2', 'MSN', 'S', 'Machine Serial Number', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('BA', 'ROR', 'Y', 'Reopen Reason', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('BA', 'ROA', 'Y', 'Reopen Authority', 2);
COMMIT;Now, this is my current query (it's changed from my first post):
SELECT ia.action_seq, ia.ici_charge_inquiry_seq, ia.action_date,
ia.serial_number, ia.reporting_office, ia.reporting_function,
ia.reporting_unit, ia.action_code, ia.machine_serial_number,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
(CASE
WHEN display_order = '1'
THEN VALUE
END) first_attribute,
(CASE
WHEN display_order = '2'
THEN VALUE
END) second_attribute
FROM ims_action ia
LEFT JOIN ims_attribute_value iav
ON iav.ia_action_seq = ia.action_seq
LEFT JOIN shared_action_attribute
ON sactatt_sact_code = sact_code
AND sactatt_sat_type = sat_type
WHERE ia.deleted = 'A';Which gives me the following results:
ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 7
45765673 09-OCT-09 B4 67089
45765674 09-OCT-09 G1 23567 W
45765674 09-OCT-09 G1 23567 23567
45765675 09-OCT-09 M3 23567 The result I WANT is similar but I want the two separate attribute columns on one row as such:
ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 P D
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E 7
45765674 09-OCT-09 G1 23567 23567 W
45765675 09-OCT-09 M3 23567 Thanks so much! -
Query with date in where clause
hi,
i have build a view with join conditions from 8 tables. the data from this view is more then 100,000
when i run the query with different clause its work with some seconds. but when i put date column in where cluase it sleeps.
eg..
where unit_id = 4 and t_id = 's09' and vb like '%amb%'
works fine.
where unit_id = 4 and t_id = 's09' and vb like '%amb%' and date between dt1 and dt2
now sleep
please ......give me some suggestionshi i have done the explain plan
the result is
Operation Object
SELECT STATEMENT ()
NESTED LOOPS ()
NESTED LOOPS ()
HASH JOIN ()
HASH JOIN ()
TABLE ACCESS (FULL) PR_PO_MST
TABLE ACCESS (FULL) PR_SUPPLIER
TABLE ACCESS (FULL) PR_PO_DTL
TABLE ACCESS (BY INDEX ROWID) INDENT_MST
INDEX (RANGE SCAN) ST_IND_MST_IDX
TABLE ACCESS (BY INDEX ROWID) ST_ITEM
Operation Object
INDEX (UNIQUE SCAN) PK_ST_ITEM
now wot do do???? -
Hi all
I have two queries and i want to join this two query
The report column should be like this
item_number WK_30 WE_311st query
select
re.item_number,
nvl(le.quantity,0) - nvl(re.quantity,0) WK_30
from BACKLOG_WEEK_WH_AFTR_ATP le, BACKLOG_ATP_GT_CW_IN re
where le.item_number =re.item_number
and to_number(substr(re.year_week,-2,2)) = to_number(to_char(sysdate,'IW'))+12nd query
select
re.item_number,
nvl(le.quantity,0) - nvl(re.quantity,0) WK_31
from BACKLOG_WEEK_WH_AFTR_ATP le, BACKLOG_ATP_GT_CW_IN re
where le.item_number =re.item_number
and to_number(substr(re.year_week,-2,2)) = to_number(to_char(sysdate,'IW'))+2Thanks in advance
RegardsHello
It sounds like you need a cumulative sum, in which case I think you'll need to go with analytics. If you could supply create table statements, some sample data and a clear example of the output you expect, it would be easier to put something together. However, I think the statement below should work although it is untested.
SELECT
item_number,
plus_1,
plus_2,
plus_3,
plus_4,
plus_5,
plus_6,
plus_7,
plus_8,
plus_9,
plus_10,
plus_11,
plus_12,
plus_13
FROM
( select
re.item_number,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+1, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_1,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+2, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_2,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+3, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_3,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+4, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_4,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+5, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_5,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+6, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_6,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+7, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_7,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+8, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_8,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+9, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_9,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+10, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_10,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+11, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_11,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+12, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_12,
sum(decode (to_number(substr(re.year_week,-2,2)), to_number(to_char(sysdate,'IW'))+13, nvl(le.quantity,0) - nvl(re.quantity,0),0))
OVER( PARTITION BY re.item_number ORDER BY to_number(substr(re.year_week,-2,2)) PLUS_13,
ROW_NUMBER() OVER(PARTITION BY re.item_number) rn
from
BACKLOG_WEEK_WH_AFTR_ATP le, BACKLOG_ATP_GT_CW_IN re
where
le.item_number =re.item_number
and
and to_number(substr(re.year_week,-2,2)) in
( to_number(to_char(sysdate,'IW'))+1,
to_number(to_char(sysdate,'IW'))+2,
to_number(to_char(sysdate,'IW'))+3,
to_number(to_char(sysdate,'IW'))+4,
to_number(to_char(sysdate,'IW'))+5,
to_number(to_char(sysdate,'IW'))+6,
to_number(to_char(sysdate,'IW'))+7,
to_number(to_char(sysdate,'IW'))+8,
to_number(to_char(sysdate,'IW'))+9,
to_number(to_char(sysdate,'IW'))+10,
to_number(to_char(sysdate,'IW'))+11,
to_number(to_char(sysdate,'IW'))+12,
to_number(to_char(sysdate,'IW'))+13
WHERE
rn = 1HTH
David -
Oracle OCI: Problem in Query with Date field
Client compiled with OCI: 10.2.0.4.0
Server: Oracle9i Enterprise Edition Release 9.2.0.4.0
The problematic query is:
SELECT CODIGO FROM LOG WHERE TEL = :telnumber AND DATE_PROC = '05-JUL-08'Table description:
SQL>describe LOG;
TEL NOT NULL VARCHAR2(15)
CODIGO NOT NULL VARCHAR2(20)
DATE_PROC NOT NULL DATEAs simple as it might look, when executed directly on the server with SQLPlus, it returns a result, but when executed from the app that uses OCI, this query returns OCI_NO_DATA always. In the beginning, the date value was also a placeholder, but I found out that even giving a literal like '05-JUL-08' didn't work. I have tried the following:
<ul>
<li>I've tried the basics: querying the DB from the client does work. It's this one that gives me trouble</li>
<li>The query: SELECT CODIGO FROM LOG WHERE TEL = :telnumber does work</li>
<li>Executing: ALTER SESSION SET NLS_DATE_FORMAT="DD-MM-YYYY"; before the query in both the server and the client. Same result: server returns data, client OCI_NO_DATA</li>
<li>Tried changing DATE_PROC format, combining this with the use of TO_DATE(). Same result.</li>
<li>Searched, searched, searched. No answer</li>
</ul>
I'm a bit desperate to find an answer, would appreciate any help and can provide as many further details as needed. Thanks.
Edited by: user12455729 on Jan 15, 2010 5:59 AM. -Formatting-Hi,
I've recreated your table and populated with your data.
I've run your select using OCILIB on a 10gR2 (client and server) and the codes runs fine and give expected results.
So the problem must resides in your code.... (i don't think it can be a OCI bug)
Here is the ocilib code :
#include "ocilib.h"
int main(void)
OCI_Connection *cn;
OCI_Statement *st;
OCI_Resultset *rs;
char msisdn[100] = "11223344";
char datetime[100] = "";
if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT))
return EXIT_FAILURE;
cn = OCI_ConnectionCreate("db", "usr", "pwd", OCI_SESSION_DEFAULT);
st = OCI_StatementCreate(cn);
OCI_Prepare(st, "SELECT "
" CODIGO_BANCO "
"FROM "
" VTA_LOG "
"WHERE "
" TELEFONO = :msisdn AND "
" FECHA_PROCESO = TO_DATE(:datetime, 'YYYYMMDDHH24MISS')");
OCI_BindString(st, "msisdn", msisdn, sizeof(msisdn)-1);
OCI_BindString(st, "datetime", datetime, sizeof(datetime)-1);
strcpy(datetime, "20080705162918");
OCI_Execute(st);
rs = OCI_GetResultset(st);
OCI_FetchNext(rs);
printf("%s\n", OCI_GetString(rs, 1));
strcpy(datetime, "20080705062918");
OCI_Execute(st);
rs = OCI_GetResultset(st);
OCI_FetchNext(rs);
printf("%s\n", OCI_GetString(rs, 1));
OCI_Cleanup();
return EXIT_SUCCESS;
}Output is :
BancoOne
BancoTwoi recreated your data with
create table VTA_LOG
TELEFONO VARCHAR2(15) NOT NULL ,
CODIGO_BANCO VARCHAR2(20) NOT NULL ,
FECHA_PROCESO DATE NOT NULL
insert into VTA_LOG values ('11223344', 'BancoOne', to_date('20080705162918', 'YYYYMMDDHH24MISS'));
insert into VTA_LOG values ('11223344', 'BancoTwo', to_date('20080705062918', 'YYYYMMDDHH24MISS'));
commit;Regards,
Vincent -
Join query with cfoutput group
Hi,
I have the problem with join query and output the goup by, can anyone helps please?
1: worked fine
<cfquery name="qOrgs" datasource="#GetDSN()#">
select org
from cat
</cfquery>
<cfoutput query="qOrgs" group="org">
#org#<br />
</cfoutput>
2: not work, not grouping and display duplicated.
<cfquery name="qOrgs" datasource="#GetDSN()#">
select org
from user u
inner JOIN cat c
on u.userid= c.userid
</cfquery>
<cfoutput query="qOrgs" group="org">
#org#<br />
</cfoutput>
ThanksTo expand on Dan's answer;
The "group" property of the <cfoutput...> tag is fairly simplistic. All it actuall does is conditionally output content whenever the value of the specified group column changes.
So if you do not use an ORDER BY clause in your SQL to group the values of that column together (or they don't naturally group because of the current state of the data in the database) then the output is probably not going to be as desired. -
Hi all,i have a doubt querying an sql statement which involves date.
1 SELECT rsh.shipment_num "File#"
2 ,mmt.transaction_date "Transaction Date"
3 FROM rcv_shipment_headers rsh,
4 ap_suppliers aps,
5 po_headers_all pha,
6 po_lines_all pla,
7 mtl_system_items_kfv msi,
8 rcv_shipment_lines rsl,
9 rcv_transactions rcv,
10 mtl_material_transactions mmt,
11 mtl_transaction_types mtt
12 WHERE rsh.vendor_id = aps.vendor_id
13 AND pha.po_header_id = pla.po_header_id
14 AND pla.item_id = msi.inventory_item_id
15 AND pha.po_header_id = rsl.po_header_id
16 and pla.po_line_id = rsl.po_line_id
17 AND rsl.shipment_header_id = rsh.shipment_header_id
18 AND rsl.item_id = msi.inventory_item_id
19 AND rsl.to_organization_id = msi.organization_id
20 AND rcv.shipment_header_id = rsh.shipment_header_id
21 AND rcv.organization_id = msi.organization_id
22 AND rcv.po_header_id = pha.po_header_id
23 AND rcv.po_line_id = pla.po_line_id
24 --and pla.org_id = msi.organization_id
25 AND rsh.SHIPMENT_NUM = 'AP1005'
26 --AND mmt.transaction_date = TO_CHAR(TO_DATE('14-SEP-2012','DD-MON-YYYY'))
27 AND rcv.transaction_type = 'DELIVER'
28 AND rcv.source_document_code = 'PO'
29 --AND rcv.subinventory = 'Vessel'
30 AND mmt.rcv_transaction_id = rcv.transaction_id
31 AND mmt.transaction_type_id = mtt.transaction_type_id
32* AND rcv.organization_id = 81
SQL> /
File# Transacti
AP1005 14-SEP-12
AP1005 14-SEP-12Now passing date
1 SELECT rsh.shipment_num "File#"
2 ,mmt.transaction_date "Transaction Date"
3 FROM rcv_shipment_headers rsh,
4 ap_suppliers aps,
5 po_headers_all pha,
6 po_lines_all pla,
7 mtl_system_items_kfv msi,
8 rcv_shipment_lines rsl,
9 rcv_transactions rcv,
10 mtl_material_transactions mmt,
11 mtl_transaction_types mtt
12 WHERE rsh.vendor_id = aps.vendor_id
13 AND pha.po_header_id = pla.po_header_id
14 AND pla.item_id = msi.inventory_item_id
15 AND pha.po_header_id = rsl.po_header_id
16 and pla.po_line_id = rsl.po_line_id
17 AND rsl.shipment_header_id = rsh.shipment_header_id
18 AND rsl.item_id = msi.inventory_item_id
19 AND rsl.to_organization_id = msi.organization_id
20 AND rcv.shipment_header_id = rsh.shipment_header_id
21 AND rcv.organization_id = msi.organization_id
22 AND rcv.po_header_id = pha.po_header_id
23 AND rcv.po_line_id = pla.po_line_id
24 --and pla.org_id = msi.organization_id
25 --AND rsh.SHIPMENT_NUM = 'AP1005'
26 AND mmt.transaction_date = TO_CHAR(TO_DATE('14-SEP-2012','DD-MON-YYYY'))
27 AND rcv.transaction_type = 'DELIVER'
28 AND rcv.source_document_code = 'PO'
29 --AND rcv.subinventory = 'Vessel'
30 AND mmt.rcv_transaction_id = rcv.transaction_id
31 AND mmt.transaction_type_id = mtt.transaction_type_id
32* AND rcv.organization_id = 81
SQL> /
no rows selectedCan anyone pls suggest me where i am doing wrong.
Any help is appreciated,
Thanks in advanceYou have already got your answer.
>
yes works out,thanks very much.May i know the reason why it didn't worked out earlier?
Thanks
>
Hope, the below example will make things more clear to you.
SQL> CREATE TABLE m003 AS
2 (SELECT 1 id,
3 To_date('14/09/2012 23:00:00', 'dd/mm/yyyy hh24:mi:ss') dt
4 FROM dual
5 UNION ALL
6 SELECT 2,
7 To_date('14/09/2012 00:00:00', 'dd/mm/yyyy hh24:mi:ss')
8 FROM dual
9 UNION ALL
10 SELECT 3,
11 To_date('14/09/2012 01:00:00', 'dd/mm/yyyy hh24:mi:ss')
12 FROM dual
13 UNION ALL
14 SELECT 4,
15 To_date('02/03/2012 23:00:00', 'dd/mm/yyyy hh24:mi:ss')
16 FROM dual);
Table created.
SQL> select * from m003;
ID DT
1 14-SEP-12
2 14-SEP-12
3 14-SEP-12
4 02-MAR-12
SQL> SELECT *
2 FROM m003
3 WHERE dt = To_char(To_date('14-SEP-2012', 'DD-MON-YYYY'));
ID DT
2 14-SEP-12 Here, 14-SEP-2012 is a string. You are converting a string to date to compare with a column data which is a date. It does not make sense to convert to string again!
SQL> select to_char(TO_DATE('14-SEP-2012','DD-MON-YYYY'),'DD-MON-YYYY HH24:MI:SS
') from dual;
TO_CHAR(TO_DATE('14-
14-SEP-2012 00:00:00As you can see, TO_DATE('14-SEP-2012','DD-MON-YYYY') returns 14-SEP-2012 00:00:00.
SQL> select * from m003
2 where dt= TO_DATE('14-SEP-2012','DD-MON-YYYY');
ID DT
2 14-SEP-12 In the above sql, it searches for the data that matches with date 14-SEP-2012 00:00:00 and hence 1 row.
if your objective is to get the records where date is 14-SEP-2012 irrespective of the time associated with it,then write..
SQL> select * from m003
2 where dt >= TO_DATE('14-SEP-2012','DD-MON-YYYY')
3 and dt < TO_DATE('14-SEP-2012','DD-MON-YYYY')+1
4 ;
ID DT
1 14-SEP-12
2 14-SEP-12
3 14-SEP-12 Now, what is the problem in below sql
SQL> select * from m003
2 where trunc(dt)= TO_DATE('14-SEP-2012','DD-MON-YYYY');
ID DT
1 14-SEP-12
2 14-SEP-12
3 14-SEP-12 The SQL above will return same result as above BUT..
In this case you are truncating the time for all the rows (ie time associated with the date will be 00:00:00) applying function trunc() which would be a bit slower. Moreover,
if there is any index on this column then use of function on the column will ignore the index (if it is not a function based index).
Hope it helps.
Regards
Biju -
Hash tables in combination with data references to the line type.
I'm having an issue with hash tables - in combination with reference variables.
Consider the following: (Which is part of a class) - it attempts to see if a particular id exists in a table; if not add it; if yes change it.
types: BEGIN OF TY_MEASUREMENT,
perfid TYPE zgz_perf_metric_id,
rtime TYPE zgz_perf_runtime,
execount TYPE zgz_perf_execount,
last_start TYPE timestampl,
END OF TY_MEASUREMENT.
METHOD START.
DATA: ls_measurement TYPE REF TO ty_measurement.
READ TABLE gt_measurements WITH TABLE KEY perfid = i_perfid reference into ls_measurement.
if sy-subrc <> 0.
"Didn't find it.
create data ls_measurement.
ls_measurement->perfid = i_perfid.
insert ls_measurement->* into gt_measurements.
endif.
GET TIME STAMP FIELD ls_measurements-last_start.
ls_measurement->execount = ls_measurement->execount + 1.
ENDMETHOD.
I get compile errors on the insert statement - either "You cannot use explicit index operations on tables with types HASHED TABLE" or "ANY TABLE". It is possible that.
If I don't dereference the type then I get the error LS_MEASUREMENT cannot be converted to the line type of GT_MEASUREMENTS.
I'm not looking to solve this with a combination of references and work ares - want a reference solution.
Thanks!
_Ryan
Moderator message - Moved to the correct forum
Edited by: Rob Burbank on Apr 22, 2010 4:43 PMI think it might work when you change it for
insert ls_measurement->* into TABLE gt_measurements.
For hashed table a new line here will be inserted according to given table key.
Regards
Marcin -
Hi,
The query has the following output which is built by multiple tables :
Cust No. Invoice Date Balance
1 01-jan-06 100
1 10-mar-06 200
1 20-mar-06 50 ----->
2 15-jan-06 25
2 02-mar-06 50
2 10-mar-06 100 ----->
Suppose if I enter the invoice date as 'MAR-06' I should get the output of two records only indicated by arrow....
1 20-mar-06 50 ----->
2 10-mar-06 100 ----->
Please let me know to frame the query.
Thanks....in your query you need to add
where TO_CHAR(TRUNC( Inoice_date, 'MONTH'), 'MON-YYYY' ) = 'MAR-2006'
By the way, you have one more mar-2006 row well two more
Cust No. Invoice Date Balance
1 01-jan-06 100
1 10-mar-06 200 ------>here
1 20-mar-06 50 ----->
2 15-jan-06 25
2 02-mar-06 50 -----> and here
2 10-mar-06 100 -----> -
*Urgent* Query with dates
Hi Gurus,
I am having problem in developing such a query which has calculations with dates. The problem is:
I have
base date for example 26-feb-2006
statring day: 4
interval: 5
input date: 15-mar-2006
Now the problem is I want to get the results from the query which will start 26-feb-2006+4 which is 02-mar-2006 and calculate the interval which is 5 days from '02-mar-2006' and run it every 5 (interval) days
02-mar-2006
07-mar-2006
12-mar-2006
I hope I have cleared everything.
Please let me know as soon as possible.
Thanks in advance.
AqilWhere is the base_date coming from?
declare
v_jobno number;
dbms_job.submit(v_jobno, 'SCHEMA_NAME.sp_my_proc();',
-- first time running I schedule for 11 pm staring in 4 days
trunc(sysdate+4)+23/24,
-- here the interval
'trunc(sysdate+5)+23/24' );
end; -
Select Query with Date comparison
Hi all,
I need to select data from Infotypes based on AEDTM.
I have an internal table which has all the records from IT0000.
I am looping into this internal table and then select data fom It0001 and IT0002 depending on the AEDTM of it0000.
loop at it_0000 into wa_0000
select * from Pa0001 into it_0001
where pernr = wa_0000-pernr
and aedtm LE wa_0000-aedtm.
endloop.
All records from IT0001 are not getting fetched.
Only records for condition aedtm = wa_0000-aedtm are getting fetched not for 'less than'.
Please let me know how this can be achieved or any pointers in this case.
Thanks,
SaherHi,
As per your logic,
Loop at it_0000.
select * from Pa0001 into it_0001
where pernr = it_0000-pernr
and aedtm <= it_0000-aedtm.
endloop.
Here the internal table it_0001 will not be appened automatically each time you run through the loop.
At the first loop for it_0000-aedtm = '20090611', the corresponding fields will be fetched.
Wnen the second loop starts for it_0000-aedtm = '20090706', the internal table fields will be replaced and it wont be appended.
Therefore after the whole loop only fields corresponding to it_0000-aedtm <= '20090806' will be present in it_0001.
Also this logic is not advisable.
As suggested use this
select * from Pa0001 into it_0001
for all entries in it_0000
where pernr = it_0000-pernr
and aedtm <= it_0000-aedtm.
which will give the correct values.
Regards,
Vikranth -
Creating a Query with Data from 4 Tables.
Hey guys. I'm having a small problem figuring out the best way for me to handle this query.
I'm trying to make a query which outputs the amount of appointments a GP has furfilled, and the total amount allowed.
I have 4 tables, for each I'm just gonna list the relevent columns:
Appointment: ID, Patient_ID.
Patient: ID, GP_ID.
GP: ID, Trust_ID.
Trust: ID, Quota.
Appointment table has 400 entries (2 per patient atm).
Patient table has 200 entries.
GP Table has 30 entries (GP's can be assigned to more than one person) .
Trust table has 6 entries.
What I need to do is, look at the appointment table and get the number of times each patient has an appointment.
Go through the patient table, and find out which GP the patient in the appointment belongs to.
Add each occurance to the correct GP.
Find out which Trust each GP belongs to, and add the total for each GP to the correct Trust.
Check the quota in the Trust table, to see if the total is more than the allowed.
I can't seem to think of an easy or simple way for me to do this. Can anyone help please? Many thanks.Hi,
That sounds like a job for JOIN.
To check the quotas against the total, use the SUM function; either the aggregate SUM or the analytic SUM, depending on your requirements.
Sorry this answer is so vague, but that's the bes I can do with the information provided so far.
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. In this case, between 2 and 10 rows of data per table should be enough to show what you need to do.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
Always say which version of Oracle you're using. -
Query with date variable selection
Greetings,
I am having problems with a SQL Query and wondering if someone could help me out. I have the following query and want to specify a WHERE clause and have the user select the date range they want to work with. If I specify a date the query runs fine. If I enter in the [%0] I get an error message saying: "incorrect syntax near '<'.
Any help would be appreciated.
select
'W' as prefix,
empid as [Employee Number] ,
U_PayrollCat as [Payroll Category Code],
'' as [Cost Center Code],
ContractID as [Job Center Code],
Segment_0 + isnull( ActSep + Segment_1, '') + isnull(ActSep + Segment_2, '')
+ isnull(ActSep + Segment_3, '') + isnull(ActSep + Segment_4, '')
+ isnull( ActSep + Segment_5, '') + isnull(ActSep + Segment_6, '')
+ isnull(ActSep + Segment_7, '') + isnull(ActSep + Segment_8, '')
+ isnull( ActSep + Segment_9, '') as [GL Account Code],
quantity as Units,
U_NBS_ITEMCOST/quantity as Rate,
U_NBS_ITEMCOST as Amount,
oclg.notes as Comments,
oclg.recontact as [WorkDate],
'' as[Department code]
from
oclg inner join
dln1 on dln1.docentry =oclg.docentry inner join
odln on odln.docentry = dln1.docentry inner join
ohem on ohem.userid = oclg.attenduser
inner join oitm on oitm.itemcode = dln1.itemcode
inner join oscl on oscl.callid = odln.U_NBS_S1Link
inner join OACT on OACT.AcctCode = dln1.cogsAcct
inner join oadm on 1=1
WHERE
oclg.recontact >= [%0] AND oclg.recontact <= [%1]Gordon,
That worked with a few modifications. Removed comma on line before FROM clause and my UDF for Payroll Category is on my OITM table. Complete Query looked like this:
SELECT 'W' as prefix, t3.empid as 'Employee Number',
t4.U_PayCat as 'Payroll Category Code',
t5.ContractID as 'Job Center Code',
t6.Segment_0 + isnull( ActSep + t6.Segment_1, '') + isnull(ActSep + t6.Segment_2, '')
+ isnull(ActSep + t6.Segment_3, '') + isnull(ActSep + t6.Segment_4, '')
+ isnull( ActSep + t6.Segment_5, '') + isnull(ActSep + t6.Segment_6, '')
+ isnull(ActSep + t6.Segment_7, '') + isnull(ActSep + t6.Segment_8, '')
+ isnull( ActSep + t6.Segment_9, '') as 'GL Account Code',
t1.quantity as Units,
t1.U_NBS_ITEMCOST/t1.quantity as Rate,
t1.U_NBS_ITEMCOST as Amount,
t0.notes as Comments,
t0.recontact as WorkDate
from dbo.oclg t0
inner join dbo.dln1 t1 on t1.docentry =t0.docentry
inner join dbo.odln t2 on t2.docentry = t1.docentry
inner join dbo.ohem t3 on t3.userid = t0.attenduser
inner join dbo.oitm t4 on t4.itemcode = t1.itemcode
inner join dbo.oscl t5 on t5.callid = t2.U_NBS_S1Link
inner join dbo.OACT t6 on T6.AcctCode = t1.cogsAcct
inner join dbo.oadm t7 on 1=1
WHERE t0.recontact >= '[%0]' AND t0.recontact <= '[%1]'
Thanks for the help,
Aaron
Maybe you are looking for
-
Tax not getting computed in Sales Order
Hi All, I have an issue in VA03 in conditions tab in Sales order. The Tax field is not getting generated. It's not calculating and showing 0,00. Can you please help me out on this for proceeding further. Thanks, pradeep Moderator Messa
-
Auto batch detmn for components in Process Order selects batch in Q status.
Hi Gurus, We have the following issue with automatic batch determination for component batches for a Process Order: Say for a Process Order it requires components A,B, and C. The issue is with component C. if the PO requires 100 Qty of C. the system
-
All of the the Windows Sidebar Apps have quit working
With the latest update today, all of my Sidebar gagdets have quit working. When I go to reinstall, I am asked what Firefox should do with them. Why? My gadgets are a windows thing.
-
Getting problem with profileId in order
Hi all, We are using DCSSampleCatalog in ATG 10.1.2 version. We are having a strange problem: in some orders, we are logged and the profileId is saved correctly, with the id that are logged in store. But sometimes, we are logged but ATG is saving ano
-
Hi, We are observing that when we set the portlet preferences from a JSP page which is included in the normal view of a portlet, the preferences are not saved. However, when we use the same code in a preference page, the settings are saved. Can any o