Help with over by clause in query.
guys i have a table like this
create table fgbtrnh ( fgbtrnh_doc_code varchar2(9),
fgbtrnh_trans_date date,
fgbtrnh_trans_amt number(17,2),
fgbtrnh_acct varchar2(6) ,
fgbtrnh_fund_code varchar2(6),
fgbtrnh_rucl_code varchar2(6) );
with data like this.
insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('J0005445','31-MAY-10','38491','6001','BD01','360098');
insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000005','01-JUL-08','38260','6001','BD01','360098');
insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000002','30-JUN-08','24425.29','6001','BD01','360125');
insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000002','30-JUN-08','48057.71','6001','BD01','360125');
insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('M0000002','30-JUN-08','90','7200','BD01','360098');i would like to get a running total of these items so i tried something like this.
select f.fgbtrnh_doc_code,f.fgbtrnh_trans_date,f.fgbtrnh_trans_amt, sum(f.fgbtrnh_trans_amt)
over
(--partition by f.fgbtrnh_doc_code
order by fgbtrnh_trans_date desc ROWS UNBOUNDED PRECEDING
--group by f.fgbtrnh_doc_code
)total
From fgbtrnh f
where f.fgbtrnh_fund_code in ('360098', '360125')
and f.fgbtrnh_rucl_code = 'BD01'
and f.fgbtrnh_acct = '6001'
order by f.fgbtrnh_trans_date desc, f.fgbtrnh_doc_codebut i end up with a result set like
"FGBTRNH_DOC_CODE", "FGBTRNH_TRANS_DATE", "FGBTRNH_TRANS_AMT", "TOTAL"
"J0005445", 31-MAY-10, 38491, 38491
"L0000005", 01-JUL-08, 38260, 76751
"L0000002", 30-JUN-08, 24425.29, 101176.29
"L0000002", 30-JUN-08, 48057.71, 149234
i would like to thave the running total to start from the bottom in other word is my total column i would like to end up with the 149234 at the top
so it would look something like so.
"FGBTRNH_DOC_CODE", "FGBTRNH_TRANS_DATE", "FGBTRNH_TRANS_AMT", "TOTAL"
"J0005445", 31-MAY-10, 38491, 149234
"L0000005", 01-JUL-08, 38260, 110743
"L0000002", 30-JUN-08, 24425.29, 72483
"L0000002", 30-JUN-08, 48057.71, 48057.71
i have tried everything and just cant seem to make this work can someone please point me in the rigth direction.
I would really appreciate the help.
Thanks
Miguel
Hi, Miguel,
mlov83 wrote:
... Also, if you uniquely order the rows, you won't need the windowing clause ("ROWS UNBOUNDED PRECEEDING"); the default ("RANGE UNBOUNDED PRECEDING") will produce exactly what you want, so you don;'t need to say it.
I dont really understand what you mean by this ? but if i take a gander are you saying that all my rows would have to be unique and then i wont have to use ("ROWS UNBOUNDED PRECEEDING")I think you got it right.
The analytic ORDER BY clause doesn't have to result in a unique ordering; there are good reasons for having a unique oprdering, and there are good reasons for not having a unique ordering.
I'm saying that if the analytic ORDER BY is unique, then you don't need to give a widnowing clause, such as "ROWS UNBOUNDED PRECEEDING".
Frank sorry if im asking some really stupid questions but i have tried and tried to read and understand "partion by" and "over" work but im not quite sure I understand yet. It's not stupid at all! Analytic functions can be very subtle and confusing.
Let's use a query based on the scott.emp table, which has seveal rows for each deptno.
-- Tell SQL*Plus to put a blank line between deptnos, just to make the output easier to read
BREAK ON deptno SKIP 1 DUPLICATES
SELECT deptno
, ename
, sal
, SUM (sal) OVER ( PARTITION BY deptno
ORDER BY sal
ROWS UNBOUNDED PRECEDING
) AS running_total
FROM scott.emp
ORDER BY deptno
, sal DESC
, ename
;Output:
` DEPTNO ENAME SAL RUNNING_TOTAL
10 KING 5000 8750
10 CLARK 2450 3750
10 MILLER 1300 1300
20 FORD 3000 10875
20 SCOTT 3000 7875
20 JONES 2975 4875
20 ADAMS 1100 1900
20 SMITH 800 800
30 BLAKE 2850 9400
30 ALLEN 1600 6550
30 TURNER 1500 4950
30 MARTIN 1250 2200
30 WARD 1250 3450
30 JAMES 950 950PARTITION BY deptno" means do a separate calculation for each distinct value of deptno. Rows with deptno=10 don't effect the results on rows where deptno=20 or deptno=30. Since there are 3 distinct values of deptno, there are 3 distinct running totals.
Notice that the aNalytic ORDER BY clause results only in a partial ordering. If there are two or more rows in the same deptno that happen to have the same sal, look what can happen:
{code}
` DEPTNO ENAME SAL RUNNING_TOTAL
... 30 TURNER 1500 4950
30 MARTIN 1250 2200
30 WARD 1250 3450
30 JAMES 950 950
{code}
MARTIN and WARD are in the same partition (deptno=30), and they both have the same sal (1250), so there is no reason why one of those rows would be considered "before" the other one. When you use a windowing clause based on ROWS, as above, and there is a tie for whcih row comes first (as there is a tie between MARTIN and WARD), then one of the rows will arbitrarily be condidered to be before the other one. In this example, it happened to chose MARTIN as the 2nd lowest sal, so running_total=2200 (= 950 + 1250) on the row for MARTIN, and running_total=3450 ( = 950 + 1250 + 1250) on the row for WARD. There's no particular reason for that; it's completely arbitrary. I might do the exact same query tomorrow, or in 10 minutes, and get running_total=2200 on WARD's row, and 3450 on MARTIN's.
However, it is no accident that MARTIN comes before WARD in the output; the *query* ORDER BY clause (which has nothing to do with the analytic ORDER BY clause) guarantees that, when two rows have the same deptno and sal, then the one with the earlier ename will come first.
Now, what's the difference between a window based on ROWS and a window bnased on RANGE?
One difference is that, when a tie occurs in the ORDER BY clause, all rows with the same value of sal get the same value for SUM (sal):
{code}
SELECT deptno
, ename
, sal
, SUM (sal) OVER ( PARTITION BY deptno
ORDER BY sal
) AS running_total
FROM scott.emp
ORDER BY deptno
, sal DESC
, ename
{code}
Notice that the only difference between the first query above and this one is that this one does not have an analytic windowing clause, so the default window, *RANGE* UNBOUNDED PRECEDING is used.
Output:
{code}
` DEPTNO ENAME SAL RUNNING_TOTAL
10 KING 5000 8750
10 CLARK 2450 3750
10 MILLER 1300 1300
20 FORD 3000 10875
20 SCOTT 3000 10875
20 JONES 2975 4875
20 ADAMS 1100 1900
20 SMITH 800 800
30 BLAKE 2850 9400
30 ALLEN 1600 6550
30 TURNER 1500 4950
30 MARTIN 1250 3450
30 WARD 1250 3450
30 JAMES 950 950
{code}
Again, look at MARTIN and WARD near the end. They both have the ame sal, so they both have the same running_total=3450 (= 950 + 1250 + 1250). This is often a desireable result, but, in your case, it seems not to be. If you want separate running_totals for MARTIN and WARD, then you eigher have to use a ROW-based window, like we did earlier, or add a tie-breaker to the ORDER BY clause, like this:
{code}
SELECT deptno
, ename
, sal
, SUM (sal) OVER ( PARTITION BY deptno
ORDER BY sal
, ename DESC -- Changed (this is the only change)
) AS running_total
FROM scott.emp
ORDER BY deptno
, sal DESC
, ename
{code}
Output:
{code}
` DEPTNO ENAME SAL RUNNING_TOTAL
10 KING 5000 8750
10 CLARK 2450 3750
10 MILLER 1300 1300
20 FORD 3000 10875
20 SCOTT 3000 7875
20 JONES 2975 4875
20 ADAMS 1100 1900
20 SMITH 800 800
30 BLAKE 2850 9400
30 ALLEN 1600 6550
30 TURNER 1500 4950
30 MARTIN 1250 3450
30 WARD 1250 2200
30 JAMES 950 950
{code}
Similar Messages
-
Newbie: help with join in a select query
Hi: I need some help with creating a select statement.
I have two tables t1 (fields: id, time, cost, t2id) and t2 (fields: id, time, cost). t2id from t1 is the primary key in t2. I want a single select statement to list all time and cost from both t1 and t2. I think I need to use join but can't seem to figure it out even after going through some tutorials.
Thanks in advance.
Rayt1 has following records
pkid, time, cost,product
1,123456,34,801
2,123457,20,802
3,345678,40,801
t2 has the following records
id,productid,time,cost
1,801,4356789,12
2,801,4356790,1
3,802,9845679,100
4,801,9345614,12
I want a query that will print following from t1 (time and cost for records that have product=801)
123456,34
345678,40
followed by following from t2 (time and cost for records that have productid=801)
4356789,12
4356790,1
9345614,12
Is this possible?
Thanks
ray -
[10g] Need help with order by clause in hierarchical query
I have the following sample data:
CREATE TABLE bill_test1
( parent_part CHAR(25)
, child_part CHAR(25)
, line_nbr NUMBER(5)
, qty_per NUMBER(9,5)
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-10',100,1);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-20',200,2);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-30',300,3);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-1',401,10);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-2',402,5);
INSERT INTO bill_test1 VALUES ('ABC-10','ABC-155',100,2);
INSERT INTO bill_test1 VALUES ('ABC-10','HARDWARE-1',200,1);
INSERT INTO bill_test1 VALUES ('ABC-155','RAW-2',100,4.8);
INSERT INTO bill_test1 VALUES ('ABC-155','HARDWARE-3',200,3);
INSERT INTO bill_test1 VALUES ('ABC-20','RAW-1',100,10.2);
INSERT INTO bill_test1 VALUES ('ABC-30','RAW-3',100,3);And the query below gives me exactly what I want, in the order I want it. However, I am wondering if there is a way to get this order without creating the SEQ column, since I don't need it in my results
SELECT part_nbr
, parent_part
, child_part
FROM (
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
, dual
CONNECT BY parent_part = PRIOR child_part
WHERE part_nbr = 'ABC-1'
ORDER BY seq
Results of above query, except with SEQ included in SELECT (just to show what I'm sorting off of):
PART_NBR PARENT_PART CHILD_PART SEQ
ABC-1 ABC-1 ABC-10 100
ABC-1 ABC-10 ABC-155 100 100
ABC-1 ABC-155 RAW-2 100 100 100
ABC-1 ABC-155 HARDWARE-3 100 100 200
ABC-1 ABC-10 HARDWARE-1 100 200
ABC-1 ABC-1 ABC-20 200
ABC-1 ABC-20 RAW-1 200 100
ABC-1 ABC-1 ABC-30 300
ABC-1 ABC-30 RAW-3 300 100
ABC-1 ABC-1 HARDWARE-1 401
ABC-1 ABC-1 HARDWARE-2 402Hi,
As long as there's only one root, you can say ORDER SIBLINGS BY, but you can't do that in a sub-query (well, you can, but usually there's no point in doing it in a sub-query). If the CONNECT BY is being done in a sub-query, there is no guarantee that the main query will preserve the hierarchical order that the sub-query provides.
The query you posted doesn't require a suib-query, so you can say:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
WHERE CONNECT_BY_ROOT b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;I said the query you posted doesn't require a sub-query. It also doesn't require dual, so I suspect what you posted is a simplification of what you're really doing, and that may need a sub-query. In particular, if you intend to GROUP BY part_nbr, then you need the sub-query. We can repeat the CONNECT_BY_ROOT expression in the WHERE clause (or, now that I think about it, use a START WITH clause instead of WHERE), but, for some reason, we can't use CONNECT_BY_ROOT in a GROUP BY clause; we need to compute CONNECT_BY_ROOT in a sub-query, give it a name (like part_nbr), and GROUP BY that column in a super-query.
This assumes that there is only one root node. ORDER SIBLINGS BY means just that: children of a common parent will appear in order, but the root nodes, who have no parents, will not necessarily be in order.
Here's what I meant by using START WITH instead of WHERE:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
START WITH b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;This should be much more efficient, because it narrows down the results before you waste time getting their descendants.
Using a START WITH clause here is analagous to me sending you an e-mail, saying "Come to a meeting a my office at 3:00."
Using a WHERE clause here is analagous to me sending an e-mail to everyone in the company, saying "Come to a meeting a my office at 3:00", and then, as people get here, telling everyone except you that they can go back.
ORDER SIBLINGS BY was introduced in Oracle 9.
Edited by: Frank Kulash on Dec 9, 2010 2:39 PM
Added version with START WITH clause -
Need Help with instr/Regexp for the query
Hi Oracle Folks
I am using Oracle
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
I have some student responses and the valid values are +/-/O(alphabet)/P and spaces at the end of the sting only not in the middle.
As per my requirement the record number 2 3,4 should be listed from the query but I am getting only one (record 3).
Can we use REG_EXP
Please help.
Thanks in advance.
Rajesh
with x as (
SELECT '+-+-POPPPPPP ' STUDENT_RESPONSE, 1 record_number FROM DUAL union all
SELECT '+--AOPPPPPP++' STUDENT_RESPONSE, 2 record_number FROM DUAL union all
SELECT '+-+- OPPPPPP--' STUDENT_RESPONSE, 3 record_number FROM DUAL union all
SELECT '+-+-9OPPPPPP ' STUDENT_RESPONSE, 4 record_number FROM DUAL )
(SELECT RECORD_NUMBER,
TRIM(STUDENT_RESPONSE) FROM X
WHERE
((INSTR (UPPER(TRIM(STUDENT_RESPONSE)),'-') =0)
OR (INSTR (UPPER(TRIM(STUDENT_RESPONSE)),'+') =0)
OR (INSTR (UPPER(TRIM(STUDENT_RESPONSE)),'O') =0)
OR (INSTR (UPPER(TRIM(STUDENT_RESPONSE)),'P') =0)
OR (INSTR (UPPER(TRIM(STUDENT_RESPONSE)),' ') !=0)
)Hi, Rajesh,
Rb2000rb65 wrote:
Hi Oracle Folks
I am using Oracle
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing optionsThanks for posting this (and the WITH clause for the sample data). That's very helpful.
I have some student responses and the valid values are +/-/O(alphabet)/P and spaces at the end of the sting only not in the middle.Are you combining the responses to several qeustions in one VARCHAR2 column? It might be better to have a separate row for each question.
As per my requirement the record number 2 3,4 should be listed from the query but I am getting only one (record 3). What exactly is your requirement? Are you trying to find the rows where student_response contains any of the forbidden characters, or where it contains a space anywhere but at the end of the string?
Can we use REG_EXPYes, but it's easy enough, and probably more efficient, to not use regular expressions in this case:
Here's one way:
SELECT record_number
, student_response
FROM x
WHERE TRANSLATE ( UPPER ( RTRIM (student_response, ' '))
, 'X+-OP'
, 'X'
) IS NOT NULL
;That is, once you remove trailing spaces and all occurrences of '+', '-', 'O' or 'P', then only the forbidden characters are left, and you want to select the row if there are any of those.
If you really, really want to use a regular expression:
SELECT record_number
, student_response
FROM x
WHERE REGEXP_LIKE ( RTRIM (student_response)
, '[^-+OP]' -- or '[^+OP-]', but not '[^+-OP]'. Discuss amongst yourselves
, 'i'
;but, I repeat, this will probably be slower than the first solution, using TRANSLATE.
Edited by: Frank Kulash on Oct 17, 2011 1:05 PM
Edited by: Frank Kulash on Oct 17, 2011 1:41 PM
The following is slightly simpler than TRANSLATE:
SELECT record_number
, student_response
FROM x
WHERE RTRIM ( UPPER ( RTRIM (student_response, ' '))
, '+-OP'
) IS NOT NULL
; -
Need help with ORDER BY clause
Hey,
I have a table:
Name: Year:
Eagle 2000
Tiger 2001
Eagle 2002
Lion 2006
Lion 1999
Fox 1991
Lion 1995
I need a query which will return in such order:
Name: Year: Position:
Eagle 2000 1
Eagle 2002 2
Fox 1991 1
Lion 1995 1
Lion 1999 2
Lion 2006 3
Tiger 2001 1
So, of course to get Name and Year in this order is quite easy:
select Name, Year from Animals order by Name, Year;
but how about Position, is there a way to count it with SQL?
any help is welcome,
SilvestrasSQL> with rt as
2 (select 'Eagle' nm, 2000 yr from dual union all
3 select 'Tiger', 2001 from dual union all
4 select 'eagle', 2002 from dual union all
5 select 'Lion', 2006 from dual union all
6 select 'Lion', 1999 from dual union all
7 select 'Fox', 1991 from dual union all
8 select 'Lion', 1995 from dual)
9 select nm,yr,row_number() over(partition by (nm) order by nm,yr) position from rt;
NM YR POSITION
Eagle 2000 1
Fox 1991 1
Lion 1995 1
Lion 1999 2
Lion 2006 3
Tiger 2001 1
eagle 2002 1
7 rows selected.
SQL> with rt as
2 (select 'Eagle' nm, 2000 yr from dual union all
3 select 'Tiger', 2001 from dual union all
4 select 'eagle', 2002 from dual union all
5 select 'Lion', 2006 from dual union all
6 select 'Lion', 1999 from dual union all
7 select 'Fox', 1991 from dual union all
8 select 'Lion', 1995 from dual)
9 select nm,yr,row_number() over(partition by lower(nm) order by nm,yr) position from rt;
NM YR POSITION
Eagle 2000 1
eagle 2002 2
Fox 1991 1
Lion 1995 1
Lion 1999 2
Lion 2006 3
Tiger 2001 1
7 rows selected.
SQL> -
I have the privilege of performing a very tedious task.
We have some home grown regular expressions in our company. I now need to expand these regular expressions.
Samples:
a = 0-3
b = Null, 0, 1
Expression: Meaning
1:5: 1,2,3,4,5
1a: 10, 11, 12, 13
1b: 1, 10, 11
1[2,3]ab: 120, 1200, 1201, ....
It get's even more inetersting because there is a possibility of 1[2,3]a.ab
I have created two base queries to aid me in my quest. I am using the SQL MODEL clause to solve this problem. I pretty confident that I should be able to convert evrything into a range and the use one of the MODEL clause listed below.
My only confusion is how do I INCREMENT dynamically. The INCREMENT seems to be a constant in both a FOR and ITERATE statement. I need to figure a way to increment with .01, .1, etc.
Any help will be greatly appreciated.
CODE:
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range with ITERATE
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
SELECT pt AS code_expression
-- , KEY
-- , min_key
-- , max_key
, m_1 AS code
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( 0 AS KEY )
MEASURES (
0 AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
RULES
-- UPSERT
ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
ORDER BY pt, m_1
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 18: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 19: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 21: 0 AS m_1
A space holder for new values.
Line 22: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 23: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Rules-
Line 26: UPSERT
This makes it possible for new rows to be created.
Line 27: ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
This reads ITERATE 100000 times or UNTIL the ITERATION_NUMBER = max_key[0] - min_key[0]
which would be 4 for '1:5', but since the ITERATION_NUMBER starts at 0, whatever follows
is repaeted 5 times.
Line 29: m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
m_1[ITERATION_NUMBER] means m_1[Value of Dimension KEY].
Thus for each row of KEY the m_1 is min_key[0] + ITERATION_NUMBER.
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range using FOR
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
, base AS
SELECT pt AS code_expression
, KEY AS code
, min_key
, max_key
, my_increment
, m_1
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( CAST(0 AS NUMBER) AS KEY )
MEASURES (
CAST(NULL AS CHAR) AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key,
.1 AS my_increment
RULES
-- UPSERT
m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
ORDER BY pt, KEY, m_1
SELECT code_expression, code
FROM base
WHERE m_1 = 'Y'
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 21: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 22: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 24: CAST(NULL AS CHAR) AS m_1
A space holder for results.
Line 25: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 26: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Line 27: .1 AS my_increment
The INCREMENT I would like to use.
Rules-
Line 30: UPSERT
This makes it possible for new rows to be created.
However seems like it is not necessary.
Line 32: m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
Where the KE value is between min_key[0] and max_key[0] set the value of m_1 to 'Y'
*/Of course, you can accomplish the same thing without MODEL using an Integer Series Generator like this.
create table t ( min_val number, max_val number, increment_size number );
insert into t values ( 2, 3, 0.1 );
insert into t values ( 1.02, 1.08, 0.02 );
commit;
create table integer_table as
select rownum - 1 as n from all_objects where rownum <= 100 ;
select
min_val ,
increment_size ,
min_val + (increment_size * n) as val
from t, integer_table
where
n between 0 and ((max_val - min_val)/increment_size)
order by 3
MIN_VAL INCREMENT_SIZE VAL
1.02 .02 1.02
1.02 .02 1.04
1.02 .02 1.06
1.02 .02 1.08
2 .1 2
2 .1 2.1
2 .1 2.2
2 .1 2.3
2 .1 2.4
2 .1 2.5
2 .1 2.6
2 .1 2.7
2 .1 2.8
2 .1 2.9
2 .1 3
15 rows selected.--
Joe Fuda
http://www.sqlsnippets.com/ -
Greetings everyone,
I'm trying to use the over function but with two sums, the point is to get the points of a sum to make a graphic that goes up and down depending on this values.
This is the first part thats working
SELECT {RegistoDeposito}.[Data],
SUM({RegistoDeposito}.[Quantidade]) over (order by {RegistoDeposito}.[Data] ASC) as total, '','',''
FROM {RegistoDeposito}
But now I need that that value gets subtracted by the values that come from this column: {Enchimentos}.[Quantidade].
I have no ideia how to do this, please help me if you can.If a few rows, here's a suggestion.
IF Object_ID('tempdb..#MovSeq','U') is not null DROP TABLE #MovSeq;
-- agrupa entradas e saídas, gerando tabela temporária
;with Movimento as (
SELECT [Date], -Quantidade
from RegistoDeposito
union all
SELECT [Date], Quantidade
from Enchimentos
SELECT [Date], Sum(Quantidade) as Quantidade
into #MovSeq
from Movimento
group by [Date];
-- cria índice para agilizar pesquisa por data
CREATE clustered INDEX I1 on #MovSeq ([Date]);
-- acumula
SELECT [Date],
Quantidade= (SELECT Sum(Quantidade) from #MovSeq as M2 where M2.[Date] <= M.[Date])
from #MovSeq as M
order by [Date];
IF Object_ID('tempdb..#MovSeq','U') is not null DROP TABLE #MovSeq;
Or
-- acumula
SELECT M1.[Date],
Sum(M2.Quantidade) as Quantidade
from #MovSeq as M1 inner join
#MovSeq as M2
on M2.[Date] <= M1.[Date])
group by M1.[Date]
order by M1.[Date];
José Diz Belo Horizonte, MG - Brasil
(Se encontrou a solução nesta resposta, ou se o conteúdo foi útil, lembre-se de marcá-la) -
Help with nvl and to_char in query
Hi, I was wondering if anyone could help me with finding the reason that the following query gives me an invalid number error:
SELECT to_char('dd/mm/yyyy',nvl(co_modified_date,co_added_date)) as d1
FROM co_allergies_record_upd
WHERE co_allergies_record_upd_id IN (
SELECT co_allergies_record_upd_id
FROM co_allergies_link_upd
WHERE co_allergies_rec_id = 42
ORDER BY nvl(co_modified_date,co_added_date) DESC
Specifically, it is the nvl(co_modified_date,co_added_date) which is causing the error. The co_added_date has a NOT NULL constraint, and both are date fields. What could be causing the error?You have missed format and data argument places in to_char():
SELECT to_char('dd/mm/yyyy',nvl(co_modified_date,co_added_date)) as d1
FROM co_allergies_record_upd
WHERE co_allergies_record_upd_id IN (
SELECT co_allergies_record_upd_id...
SQL> select to_char('dd/mm/yyyy',sysdate) from dual;
select to_char('dd/mm/yyyy',sysdate) from dual
ERROR at line 1:
ORA-01722: invalid number
SQL> select to_char(sysdate,'dd/mm/yyyy') from dual;
TO_CHAR(SY
20/12/2006Rgds. -
Help with PL/SQL returning SQL query for Report
Hi
I have got a report which I have formatted as PL/SQL function body returning SQL query.
I have the following code
declare
q VARCHAR2(32000); -- query
w VARCHAR2(4000) ; -- where clause
begin
q := 'select min(identified_date) first_identified,' ||
' max(actual_resolution_date) last_closed,' ||
' count("HELPDESK_CALL_ID) total_issues,' ||
' from tbl_helpdesk_calls';
if :P9_call_type != '-1' then
w := 'HELPDESK_CALL_TYPE_ID = :P9_call_type';
end if;
q := q || ' WHERE '|| w;
return q;
end;
When I apply changes I get this error message
Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing. ORA-00972: identifier is too long
Any Idea where I maybe going wrong?thanks its compiling now but when I run the page I get this error message in the reports region
failed to parse SQL query:
ORA-00933: SQL command not properly ended
This is my code that I have at the momment.
declare
q VARCHAR2(32000); -- query
w VARCHAR2(4000) ; -- where clause
we VARCHAR2(1) := 'N'; -- identifies if where clause exists
begin
q := 'select min(identified_date) first_identified,' ||
' max(actual_resolution_date) last_closed,' ||
' count(HELPDESK_CALL_ID) total_issues,' ||
' sum(decode(status,''Open'',1,0)) open_issues, ' ||
' sum(decode(status,''On-Hold'',1,0)) onhold_issues,' ||
' sum(decode(status,''Closed'',1,0)) closed_issues,' ||
' sum(decode(status,''Open'',decode
(priority,''High'',1,0),0)) open_high_prior,' ||
' sum(decode(status,''Open'',decode
(priority,''Medium'',1,0),0)) open_medium_prior, '||
' sum(decode(status,''Open'',decode
(priority,''Low'',1,0),0)) open_low_prior '||
' from tbl_helpdesk_calls';
if :P9_call_type != '-1' then
w := 'where HELPDESK_CALL_TYPE_ID = :P9_call_type';
we := 'Y';
end if;
if we = 'Y' then
q := q ||w;
end if;
return q;
end;
I have a select list with a list of reports. what I am trying to do build an sql depending on what the :p9_call_type value is. -1 represents the display value of -All Reports- so if the user selects all reports it should display all results thus removing the where clause. However as my code stands when I user clicks on all reports he get the correct results for all reports. If the user selects anything else they get the error message above. -
Gurus,
I have to create a ACCOUNTS PAYABLE AGED INVOICE REPORT where I need to to know the Future, Over 30 days (1-29), Over 60 (30-59),Over 90 (60-89). How can I have this info in the report. What are the steps that I need to follow. It's a urgent report. I dont any columns related to Over 30 days........ Is there way to write so sql on the Current date to get that info.
Please Help.First of all, I think you mean "elaborate" not "allowbarate." ;)
What you need is the date column that represents where the customer payable invoice stands "today," say "INVOICE_DATE." There is a repository variable called CURRENT_DATE which houses the "current date" so you don't have to build it.
1) Click on the fx button of the INVOICE_DATE column and enter: TIMESTAMPDIFF(SQL_TSI_DAY, CURRENT_DATE, INVOICE_DATE)
This column will now house the difference between the two dates.
To determine the days an account is delinquent, create BINS as follows:
2) Click on the fx column of the above column you have and then click on the BINS tab.
3) Click on "Add BIN" and in the next window, choose the operand "less than or equal to" and for the value, enter 30.
4) Click "OK" and name this BIN, "0-29 Days."
Repeat this for the rest of your date breakpoints and you now have column that categorizes your measure by what category it falls in.
Edited by: David_T on Sep 29, 2010 7:29 AM -
Help with ORBER BY in my query when negative numbers are involved
hi,
I have
SELECT *
FROM my_table
WHERE age = 5
ORDER BY photoSmall DESC
my_table looks like this:
key | age | photoSmall
1 25 2
2 25 3
3 25 1
4 25 -1
now, i would expect my results to be ordered as follows:
firstly record 2 (because it has the highest "photoSmall"
value of 3
then record 1 (it has the next highest "photoSmall" value of
2)
then record 3 ("photoSmall" being 1)
finally record 4 ("photoSmall" of -1 being the lowest value
of all..
but no!
it seems CF is treating -1 and 1 as being the same, how odd
do i need to amend my query to:
SELECT *
FROM my_table
WHERE age = 5
ORDER BY photoSmall DESC
CFpositive_numbers_are_greater_than_negative_numbers=YES ??
any help would be greatly appreciated - thanks very much
indeed.Thank you both very much for your help. I tried Pauls fix but
alas my access db
didn't like the "cast(photoSmall as int" concept (or at least
i couldnt get it
to work)
so in the end i did what i should have done in the first
place and changed the
photosmall var to a numeric rather than a text one.
i was forgetting that whilst CF doesnt seem to care what
"type" of variable
you give it it just gets on and "does the maths", of course
it is access that
is ordering my results
so thanks very much - this one is now fixed - cheers -
Need some help with a bottom up recursive query
I need to query some hierarchical data. I've written a recursive query that allows me to examine a parent and all it's related children using an adjacency data model. The scenario is to allow users to track how columns are populated in an ETL process. I've
set up the sample data so that there are two paths:
1. col1 -> col2 -> col3 -> col6
2. col4 - > col5
You can input a column name and get everything from that point downstream. The problem is, you need to be able to start at the bottom and work your way up. Basically, you should be able to put in col6 and see how the data got from col1 to col6. I'm not sure
if it's a matter of rewriting the query or changing the schema to invert the relationships. Any input is welcome. Sample code below.
DECLARE @table_loads TABLE (column_id INT, parent_id INT, table_name VARCHAR(25), column_name VARCHAR(25))
DECLARE @column_name VARCHAR(10)
INSERT INTO @table_loads(column_id, parent_id, table_name, column_name)
SELECT 1,NULL,'table1','col1'
UNION ALL
SELECT 2,1,'table2','col2'
UNION ALL
SELECT 3,2,'table3','col3'
UNION ALL
SELECT 4,NULL,'table4','col4'
UNION ALL
SELECT 5,4,'table5','col5'
UNION ALL
SELECT 6,3,'table6','col6'
SELECT * FROM @table_loads
SET @column_name = 'col1'
WITH load_order(column_id, parent_id,table_name, column_name)
AS(
SELECT column_id, parent_id,table_name, column_name
FROM @table_loads
WHERE column_name = @column_name
UNION ALL
SELECT tl.column_id, tl.parent_id, tl.table_name, tl.column_name
FROM load_order lo
JOIN @table_loads tl
ON lo.column_id = tl.parent_id
SELECT * FROM load_orderGot it. It required a VERY subtle change in the join code:
WITH load_order(column_id, parent_id,table_name, column_name)
AS(
SELECT column_id, parent_id,table_name, column_name
FROM @table_loads
WHERE column_name = @column_name
UNION ALL
SELECT tl.column_id, tl.parent_id, tl.table_name, tl.column_name
FROM @table_loads tl
JOIN load_order lo
ON lo.parent_id = tl.column_id
SELECT * FROM load_order -
Need Help With ACS LDAP setup to Query AD
I have 2 Win 2003 ADs, one of them is configured and working under Windows Database (using remote agent) configuration. I am trying to setup the second AD with Generic LDAP setup. I want to know what exactly I should use in the fields UserObjectType and Class, and GroupObjectType and Class for Windows 2003 AD. All Cisco documents give example of Netscape LDAP syntax. I was told by our server admin. what to put under Admin DN, CN=myid,OU=mygroup,OU=myorg,DC=mydomain,DC=com
I have both user & group directory subtree fields filled with DC=mydomain,DC=com.
I am using the ip address for Primary LDAP server, and port is 389, LDAP version 3 is checked.
Is any of these DC, OU, etc. case sensitive?
With all entries that I have tried, when I go to map a group, I am getting error "LDAP server NOT reachable. Please check the configuration". My ACS can ping the domain controller's IP address fine.
Please help. Thank you in advance,
MuraliMurali,
These references may help...
http://download.microsoft.com/download/3/d/3/3d32b0cd-581c-4574-8a27-67e89c206a54/uldap.doc
http://www.microsoft.com/technet/archive/winntas/plan/dda/ddach02.mspx?mfr=true
http://technet.microsoft.com/en-us/library/aa996205.aspx
Regards,
Richard -
Help with Date function in sql query....
My question I guess is really 2...I'm trying to use the date function as a comparison in my WHERE clause in my sql command.
1. My date format is dd-MMM-yy eg. (01-Apr-06) ... my problem is the Apr is lower case where my field in the database is 01-APR-06 so when I compare 01-Apr-06 to 01-APR-06 is doesnt find any rows. Is there away that I can make the Apr all upper case so that it is APR.
2. My second problem is getting this "date" field to work in my sql stmt I keep getting errors and it works fine if I take my attempts at trying to compare the date.
--------------Date Code----------------------------------------------------------
<%!
String getFormattedDate(java.util.Date d)
SimpleDateFormat simpleDate = new SimpleDateFormat("01-MMM-yy");
return simpleDate.format(d);
%>
<%
java.util.Date d = new java.util.Date();
String dateString = getFormattedDate (d);
%>
---------------------------Sql statment------------------------------------------
ResultSet rset = stmt.executeQuery ("SELECT name " + " FROM table where rdate = '01-APR-06' order by name ");
Currently Im just hard coding the date but I need to make it so it uses the date code...so....
rdate should equal the date from the formatted date in upper case
something like
rdate = <%= dateString %>
Thanks in advance for any ideas anyone may have...There are sql functions upper & lower.
SELECT name FROM table where upper(rdate) = '01-APR-06' order by name Or you could convert the date to a string, and use the toUpperCase & toLowerCase java.lang.String methods. It doesn't make much of a difference--do you want the java compiler to do the string conversion or the database? -
Need Help with Details of A/R Query "0FIAR_C03_Q0005"
Hello Gurus:
Can anyone please explain the logic behind the calculation of the buckets in the Business Content Query
"0FIAR_C03_Q0005". I want to add a column to the report "Number of Days". Not sure of the logic I can
use to calculate this. Can some one please suggest....?
Thanks.....PBSWI believe that they take 0DEB_CRE_LC (Debit/Credit Amount) and restrict by value range for 0NETDUEDATE. They then take variable 0DAT and offset accordingly for each of the time buckets.
e.g. 0NETDUEDATE [] 0DAT-1 - 0DAT-30
Also, crucially, you must set 0FI_DOCSTAT to characteristics restriction and filter to include only "O".
Edited by: Khaled McGonnell on Jan 29, 2010 2:51 PM
Maybe you are looking for
-
Challenger for a serious troubleshooter - shuffles thru songs...
For some reason the Ipod will play thru an album or shuffle song lists but will not acutally play songs. All of the song info comes up on the screen but it just changes to the next song without playing. I also cannot get the ipod to reset. When plugg
-
File Vault Won't Decrypt - operation fails in final minutes
I'm trying to turn off file vault. File vault said I didn't have enough room on my hard drive so I followed Apple's instructions to go into safe mode, make a sparse disk image on an ext drive and then drag and drop the encrypted home folder into the
-
[SOLVED] problem getting a clock in trayer
Hi I have installed trayer and I'm trying to get a clock for the tray. I installed lalcal 1.0-1 but i can't get it to run, when I try i get: [chrono@krono ~]$ lalcal bash: lalcal: command not found I'm running trayer from openbox autostart. (sleep
-
Why can't I download the create pdf app?
-
( name-service call wait ) event is amoung the top 5 wait events
10.2.0.3 2node- RAC When I check the wait event in the active session wait event the sessions can be see that they are blocked by the LMON process. The wait event appears only on one node. It is very hard to find information on the net or on the meta