Stuck with this SQL requirement
Ok here's the basic test data for my requirement:
with test_data as
select to_date('15/12/2008','dd/mm/yyyy') as start_date, to_date('15/12/3000','dd/mm/yyyy') as end_date from dual
select *
from test_data;
START_DATE END_DATE
15-12-2008 15-12-3000We work with a pattern, which is divided in two parts:
The first week : the first 7 days of the pattern, starting from START_DATE
The Second week : the 7 days that follow the first week (self explanatory)
I've got a requirement that says that if I'm supplied with a date, I have to find out what pattern (first or second week) the supplied date falls in.
so, our pattern for test_data is:
15-12-2008 : First day of 1st week
16-12-2008 : Second day of 1st week
17-12-2008 : Third day of 1st week
18-12-2008 : Fourth day of 1st week
19-12-2008 : Fifth day of 1st week
20-12-2008 : Sixth day of 1st week
21-12-2008 : Seventh day of 1st week
22-12-2008 : First day of second week
23-12-2008 : Second day of second week
28-12-2008 : Seventh day of second week
============================== end of pattern =================================
29-12-2008 : Start of First day of 1st week
Now, if my date supplied is 16 Dec 2008, my sql should return something like: "First Week".
If my date supplied is 24-12-2008, my sql should return "Second week".
If my date supplied is 29-12-2008, my sql should return "First Week".
phew, I thought of a connect by, but this wouldn't do the trick I think because the comparison is between columns and no rows. No clue.. I could only got til using 16/12/2008 as test date, but it doesn't work in all cases :-(:
with test_data as
select to_date('15/12/2008','dd/mm/yyyy') as start_pattern, to_date('15/12/3000','dd/mm/yyyy') as end_pattern from dual
select
start_pattern,
start_pattern + 7,
case when to_date('16/12/2008','dd/mm/yyyy') between start_pattern and start_pattern + 7 then
'first'
else
'second'
end week_it_belongs_in_pattern
from test_data
START_PATT START_PATT WEEK_I
15-12-2008 22-12-2008 firstEdited by: user9541973 on Nov 18, 2008 8:57 PM
Solution
SELECT X SO , PP PATERN
FROM DUAL
MODEL
DIMENSION BY (TO_DATE(&DT1,'YYYY-MM-DD') X)
MEASURES (1 Y, 'FIRST WEEK' PP)
(Y[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=0,
PP[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=
DECODE(MOD(CV(X)- TO_DATE(&DT1,'YYYY-MM-DD'),7),0,'First',1,'Second ',2,
'Third',3,'Fourth',4,'Fifth',5,'Sixth',6,'Seventh')||
' day of '||
CASE WHEN MOD(TO_CHAR(CV(X),'IW'),2)= 1 THEN
'first week'
ELSE 'second week' END )
Demo
SQL> SELECT X SO , PP PATERN
2 FROM DUAL
3 MODEL
4 DIMENSION BY (TO_DATE(&DT1,'YYYY-MM-DD') X)
5 MEASURES (1 Y, 'FIRST WEEK' PP)
6 (Y[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=0,
7 PP[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=
8 DECODE(MOD(CV(X)- TO_DATE(&DT1,'YYYY-MM-DD'),7),0,'First',1,'Second ',2,
9 'Third',3,'Fourth',4,'Fifth',5,'Sixth',6,'Seventh')||
10 ' day of '||
11 CASE WHEN MOD(TO_CHAR(CV(X),'IW'),2)= 1 THEN
12 'first week'
13 ELSE 'second week' END );
Entrez une valeur pour dt1 : '2008-12-15'
ancien 4 : DIMENSION BY (TO_DATE(&DT1,'YYYY-MM-DD') X)
nouveau 4 : DIMENSION BY (TO_DATE('2008-12-15','YYYY-MM-DD') X)
Entrez une valeur pour dt1 : '2008-12-15'
Entrez une valeur pour dt2 : '2009-02-15'
ancien 6 : (Y[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=0,
nouveau 6 : (Y[FOR X FROM DATE '2008-12-15' TO DATE '2009-02-15' INCREMENT INTERVAL '1' DAY ]=0,
Entrez une valeur pour dt1 : '2008-12-15'
Entrez une valeur pour dt2 : '2009-02-15'
ancien 7 : PP[FOR X FROM DATE &DT1 TO DATE &DT2 INCREMENT INTERVAL '1' DAY ]=
nouveau 7 : PP[FOR X FROM DATE '2008-12-15' TO DATE '2009-02-15' INCREMENT INTERVAL '1' DAY ]=
Entrez une valeur pour dt1 : '2008-12-15'
ancien 8 : DECODE(MOD(CV(X)- TO_DATE(&DT1,'YYYY-MM-DD'),7),0,'First',1,'Second ',2,
nouveau 8 : DECODE(MOD(CV(X)- TO_DATE('2008-12-15','YYYY-MM-DD'),7),0,'First',1,'Second ',2,
SO PATERN
2008-12-15 First day of first week
2008-12-16 Second day of first week
2008-12-17 Third day of first week
2008-12-18 Fourth day of first week
2008-12-19 Fifth day of first week
2008-12-20 Sixth day of first week
2008-12-21 Seventh day of first week
2008-12-22 First day of second week
2008-12-23 Second day of second week
2008-12-24 Third day of second week
2008-12-25 Fourth day of second week
SO PATERN
2008-12-26 Fifth day of second week
2008-12-27 Sixth day of second week
2008-12-28 Seventh day of second week
2008-12-29 First day of first week
2008-12-30 Second day of first week
2008-12-31 Third day of first week
2009-01-01 Fourth day of first week
2009-01-02 Fifth day of first week
2009-01-03 Sixth day of first week
2009-01-04 Seventh day of first week
2009-01-05 First day of second week
SO PATERN
2009-01-06 Second day of second week
2009-01-07 Third day of second week
2009-01-08 Fourth day of second week
2009-01-09 Fifth day of second week
2009-01-10 Sixth day of second week
2009-01-11 Seventh day of second week
2009-01-12 First day of first week
2009-01-13 Second day of first week
2009-01-14 Third day of first week
2009-01-15 Fourth day of first week
2009-01-16 Fifth day of first week
SO PATERN
2009-01-17 Sixth day of first week
2009-01-18 Seventh day of first week
2009-01-19 First day of second week
2009-01-20 Second day of second week
2009-01-21 Third day of second week
2009-01-22 Fourth day of second week
2009-01-23 Fifth day of second week
2009-01-24 Sixth day of second week
2009-01-25 Seventh day of second week
2009-01-26 First day of first week
2009-01-27 Second day of first week
SO PATERN
2009-01-28 Third day of first week
2009-01-29 Fourth day of first week
2009-01-30 Fifth day of first week
2009-01-31 Sixth day of first week
2009-02-01 Seventh day of first week
2009-02-02 First day of second week
2009-02-03 Second day of second week
2009-02-04 Third day of second week
2009-02-05 Fourth day of second week
2009-02-06 Fifth day of second week
2009-02-07 Sixth day of second week
SO PATERN
2009-02-08 Seventh day of second week
2009-02-09 First day of first week
2009-02-10 Second day of first week
2009-02-11 Third day of first week
2009-02-12 Fourth day of first week
2009-02-13 Fifth day of first week
2009-02-14 Sixth day of first week
2009-02-15 Seventh day of first week
63 ligne(s) sélectionnée(s).
SQL> Edited by: Salim11 on 2008-11-19 08:16
Edited by: Salim11 on 2008-11-19 08:17
Edited by: Salim11 on 2008-11-19 08:18
Similar Messages
-
iCloud backup is unable to access my account, because email I used for iCloud account is been deleted. And my iPad is stuck with this note on a screen, can't go Settings. How do I delete or edit my iCloud account?
You can eirther I think go on ITunes or if you can get to settings you would just go to iCloud.
-
ASR Hyper-v (VMM) to Azure and we are stuck with this error while preparing the VMM Server
We are stuck with this error while installing ASR provider and registering with Azure Vault, can i get some help on this
Error:
NO Vaults could be retried for the registration key. Please ensure that
1, your registration key has not expired.You can re-downloading registration key from Azure site Recovery portal
2, Your system clock is not out of sync with the selected system time zone
System Clock is set to IST and Azure to southeastasiaHi,
Could you please ensure that you have downloaded the latest registration key from the portal?
Also ensure that the machine from where you are accessing the portal and the VMM server has the right time according to your time zone.
Thank you,
Ruturaj -
What's wrong with this SQL?
what's wrong with this SQL?
Posted: Jan 16, 2007 9:35 AM Reply
Hi, everyone:
when I insert into table, i use the fellowing SQL:
INSERT INTO xhealthcall_script_data
(XHC_CALL_ENDED, XHC_SWITCH_PORT, XHC_SCRIPT_ID, XHC_FAX_SPECIFIED)
VALUES (SELECT TO_DATE(HH_END_DATE||' '||HH_END_TIME,'MM/DD/YY HH24:MI:SS'), HH_SWITCHPORT, HH_SCRIPT,'N'
FROM tmp_healthhit_load WHERE HH_SCRIPT !='BROCHURE' UNION
SELECT TO_DATE(HH_END_DATE||' '||HH_END_TIME,'MM/DD/YY HH24:MI:SS'), HH_SWITCHPORT, HH_SCRIPT,'N' FROM tmp_healthhit_load WHERE HH_SCRIPT !='BROCHURE');
I always got an error like;
VALUES (SELECT TO_DATE(HH_END_DATE||' '||HH_END_TIME,'MM/DD/YY HH24:MI:SS'), HH_SWITCHPORT,
ERROR at line 3:
ORA-00936: missing expression
but I can't find anything wrong, who can tell me why?
thank you so much in advance
mpowel01
Posts: 1,516
Registered: 12/7/98
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 9:38 AM in response to: jerrygreat Reply
For starters, an insert select does not have a values clause.
HTH -- Mark D Powell --
PP
Posts: 41
From: q
Registered: 8/10/06
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 9:48 AM in response to: mpowel01 Reply
Even I see "missing VALUES" as the only error
Eric H
Posts: 2,822
Registered: 10/15/98
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 9:54 AM in response to: jerrygreat Reply
...and why are you doing a UNION on the exact same two queries?
(SELECT TO_DATE(HH_END_DATE||' '||HH_END_TIME,'MM/DD/YY HH24:MI:SS') ,HH_SWITCHPORT ,HH_SCRIPT ,'N' FROM tmp_healthhit_load WHERE HH_SCRIPT !='BROCHURE' UNION SELECT TO_DATE(HH_END_DATE||' '||HH_END_TIME,'MM/DD/YY HH24:MI:SS') ,HH_SWITCHPORT ,HH_SCRIPT ,'N' FROM tmp_healthhit_load WHERE HH_SCRIPT !='BROCHURE');
jerrygreat
Posts: 8
Registered: 1/3/07
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 9:55 AM in response to: mpowel01 Reply
Hi,
thank you for your answer, but the problem is, if I deleted "values" as you pointed out, and then execute it again, I got error like "ERROR at line 3:
ORA-03113: end-of-file on communication channel", and I was then disconnected with server, I have to relogin SQLplus, and do everything from beganing.
so what 's wrong caused disconnection, I can't find any triggers related. it is so wired?
I wonder if anyone can help me about this.
thank you very much
jerry
yingkuan
Posts: 1,801
From: San Jose, CA
Registered: 10/8/98
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 9:59 AM in response to: jerrygreat Reply
Dup Post
jerrygreat
Posts: 8
Registered: 1/3/07
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 10:00 AM in response to: Eric H Reply
Hi,
acturlly what I do is debugging a previous developer's scipt for data loading, this script was called by Cron work, but it never can be successfully executed.
I think he use union for eliminating duplications of rows, I just guess.
thank you
jerry
mpowel01
Posts: 1,516
Registered: 12/7/98
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 10:03 AM in response to: yingkuan Reply
Scratch the VALUES keyword then make sure that the select list matches the column list in number and type.
1 insert into marktest
2 (fld1, fld2, fld3, fld4, fld5)
3* select * from marktest
UT1 > /
16 rows created.
HTH -- Mark D Powell --
Jagan
Posts: 41
From: Hyderabad
Registered: 7/21/06
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 10:07 AM in response to: jerrygreat Reply
try this - just paste the code and give me the error- i mean past the entire error as it is if error occurs
INSERT INTO xhealthcall_script_data
(xhc_call_ended, xhc_switch_port, xhc_script_id,
xhc_fax_specified)
SELECT TO_DATE (hh_end_date || ' ' || hh_end_time, 'MM/DD/YY HH24:MI:SS'),
hh_switchport, hh_script, 'N'
FROM tmp_healthhit_load
WHERE hh_script != 'BROCHURE'
UNION
SELECT TO_DATE (hh_end_date || ' ' || hh_end_time, 'MM/DD/YY HH24:MI:SS'),
hh_switchport, hh_script, 'N'
FROM tmp_healthhit_load
WHERE hh_script != 'BROCHURE';
Regards
Jagan
jerrygreat
Posts: 8
Registered: 1/3/07
Re: what's wrong with this SQL?
Posted: Jan 16, 2007 11:31 AM in response to: Jagan Reply
Hi, Jagan:
thank you very much for your answer.
but when I execute it, I still can get error like:
ERROR at line 1:
ORA-03113: end-of-file on communication channel
so wired, do you have any ideas?
thank you very muchAnd this one,
Aother question about SQL?
I thought I already told him to deal with
ORA-03113: end-of-file on communication channel
problem first.
There's nothing wrong (syntax wise) with the query. (of course when no "value" in the insert) -
Can somebody help me install IOS 6.1.3 back to my iPhone 4. IOS 7 or 7.0.4 is not smooth enough as perfect as IOS 6.1.3. I am stuck with this OS, every app gives a break for 4-5 seconds to open up. And playing games in this OS using iPhone 4 is really crazy. Very much disappointed that I am not able to use IOS 7 and cant go back to what I need.
Mani Dinesh wrote:
Can somebody help me install IOS 6.1.3 back to my iPhone 4.
Downgrading is not supported by Apple.
Mani Dinesh wrote:
...every app gives a break for 4-5 seconds to open up. ...
See this discussion...
https://discussions.apple.com/message/23731048#23731048 -
I have an emac running 10.5.8 I purchased a copy of snow leopard from apple. upon attempting the install i read that the computer is not an intel. I believe this is a power PC? Is there a way to upgrade to the snow leopard or am I stuck with this version 10.5.8? Thank you for any help.
As Niel says, no way to go past 10.5.8 on your Mac, but there is a more upto date Browser...
TenFourFox is the most up to date browser for our PPCs, they even have G4 & G5 optimized versions...
http://www.floodgap.com/software/tenfourfox/ -
Im stuck with this message "no bootable device, insert boot disk and press any key". Now i want to go back to mac os but everytime i turn on my laptop that message appear..kindly help... Please .... Im using my usb as bootable device but it cant be detected..
Reboot, hold the option key down, select OSX when the startup manager appears.
-
Whats wrong with this sql statement ??
Hello all, I am trying to run the below query out of persheet(tanel poder) performance excel chart...but i get below error...db is on 9.2
what is wrong with this sql statement ?
http://blog.tanelpoder.com/2008/12/28/performance-visualization-made-easy-perfsheet-20-beta/
select * from (
with fsq as (
select /*+ materialize */
i.dbid
, i.instance_name
, i.instance_number
-- , trunc(s.snap_time, 'DD') DAY
-- , to_number(to_char(s.snap_time, 'HH24')) HOUR
-- -- , to_char(s.snap_time, 'MI') MINUTE
-- , 0 MINUTE
, trunc(
lag(s.snap_time, 1)
over(
partition by
v.dbid
, i.instance_name
, v.instance_number
, v.event
order by
s.snap_time
, 'HH24'
) SNAP_TIME
, v.event_type EVENT_TYPE
, v.event EVENT_NAME
, nvl(
decode(
greatest(
time_waited_micro,
nvl(
lag(time_waited_micro,1,0)
over(
partition by
v.dbid
, i.instance_name
, v.instance_number
, v.event
order by v.snap_id
, time_waited_micro
time_waited_micro,
time_waited_micro - lag(time_waited_micro,1,0)
over (
partition by
v.dbid
, i.instance_name
, v.instance_number
, v.event
order by v.snap_id
time_waited_micro
, time_waited_micro
) / 1000000 SECONDS_SPENT
, total_waits WAIT_COUNT
from
(select distinct dbid, instance_name, instance_number from stats$database_instance) i
, stats$snapshot s
, ( select
snap_id, dbid, instance_number, 'WAIT' event_type, event, time_waited_micro, total_waits
from
stats$system_event
where
event not in (select event from stats$idle_event)
union all
select
snap_id, dbid, instance_number,
case
when name in ('CPU used by this session', 'parse time cpu', 'recursive cpu usage') then 'CPU'
when name like 'OS % time' then 'OS'
else 'STAT'
end,
name , value, 1
from
stats$sysstat
-- where name in ('CPU used by this session', 'parse time cpu', 'recursive cpu usage')
-- or name like('OS % time')
-- or 1 = 2 -- this will be a bind variable controlling whether all stats need to be returned
) v
where
i.dbid = s.dbid
and i.dbid = v.dbid
and s.dbid = v.dbid
and s.snap_id = v.snap_id
and s.snap_time between '%FROM_DATE%' and '%TO_DATE%'
and i.instance_name = '%INSTANCE%'
select * from (
select
instance_name
, instance_number
, snap_time
, trunc(snap_time, 'DD') DAY
, to_char(snap_time, 'HH24') HOUR
, to_char(snap_time, 'MI') MINUTE
, event_type
, event_name
, seconds_spent
, wait_count
, ratio_to_report(seconds_spent) over (
-- partition by (to_char(day, 'YYYYMMDD')||to_char(hour,'09')||to_char(minute, '09'))
partition by (snap_time)
) ratio
from fsq
where
snap_time is not null -- lag(s.snap_time, 1) function above will leave time NULL for first snapshot
-- to_char(day, 'YYYYMMDD')||to_char(hour,'09')||to_char(minute, '09')
-- > ( select min(to_char(day, 'YYYYMMDD')||to_char(hour,'09')||to_char(minute, '09')) from fsq)
where ratio > 0
order by
instance_name
, instance_number
, day
, hour
, minute
, event_type
, seconds_spent desc
, wait_count desc
Error at line 6
ORA-00604: error occurred at recursive SQL level 1
ORA-00972: identifier is too longHi Alex,
Subquery factoring a.k.a. the with-clause should be possible on 9.2:
http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/statements_103a.htm#2075888
(used it myself as well on 9.2)
@OP
I recall having problems myself using PL/SQL Developer and trying to get the with clause to work on 9.2 some years ago.
A workaround might be to create a view based on the query.
Also, your error message is "ORA-00972: identifier is too long"...
http://download.oracle.com/docs/cd/B19306_01/server.102/b14219/e900.htm#sthref419
Can't test things currently, no 9.2 available at the moment, but perhaps tomorrow I'll have a chance. -
I'm stuck with this message : en attente d'éléments à copier (étape 6 sur 6).
Hi ! I'm from Québec, Canada, so maybe there's a lot of mistakes in the following.
I've download IOS.5 this last sunday, and since everytime I sync my Ipod I'm stuck with this message in my Itunes:
En attend d'éléments à copier (étape 6 sur 6)
Can I unplug my Ipod even if it's not written : OK pour déconnecter.
Help me please, or fix that bug with an update !
Thanks a lot.Apple loops and jingles are free for you to use, here's the corresponding Apple document:
http://support.apple.com/kb/HT2931 -
i have stuck in this query. it is giving compile error that v_customerloop invalid identifier. this does not make sense because if i comment the sql, it runs fine and i can actually see the count in the dbms output. i tried commenting out some of the where clauses but cannot pinpoint where i am making a mistake.
can some one see if i am doing something out of ordinary.
declare
-- Local variables here
o_errorcode NUMBER;
o_errortext VARCHAR2(1000);
o_LoopId NUMBER;
i_CustomerLoop Kroner.Pkgsldcommon.T_CUSTOMERLOOPTYPE;
To_CustomerLoop Kroner.Pkgsldcommon.T_CUSTOMERLOOPTYPE;
v_sql VARCHAR2(3000);
v_CustomerLoop Kroner.t_CustomerLoopElement := Kroner.t_CustomerLoopElement();
begin
i_CustomerLoop(1).Cable := '138-2';
i_CustomerLoop(1).coup := '501';
i_CustomerLoop(1).TermSysID := 1178050;
i_CustomerLoop(1).CentralOfficeName := 'TOROON45';
i_CustomerLoop(2).Cable := '138-2';
i_CustomerLoop(2).coup := '503';
i_CustomerLoop(2).TermSysID := 1178052;
i_CustomerLoop(2).CentralOfficeName := 'TOROON45';
FOR i IN 1..i_CustomerLoop.COUNT -- Create a instance of Kroner.o_CustomerLoopElement
LOOP
v_CustomerLoop.Extend();
v_CustomerLoop(i) := Kroner.o_CustomerLoopElement(co_clli => i_CustomerLoop(i).CentralOfficeName,
cable => i_CustomerLoop(i).Cable,
coup => i_CustomerLoop(i).coup,
termsysid => i_CustomerLoop(i).TermSysID,
landing_number => i
END LOOP;
dbms_output.put_line('v_CustomerLoop length' || v_CustomerLoop.Count);
v_sql:= 'select loop_f1.loopid
from nrms_interface.wdn_landing seg_f1, nrms_interface.wdn_loop_landing_association assoc_f1, nrms_interface.wdn_potential_loop_makeup loop_f1,
nrms_interface.wdn_landing seg_fx, nrms_interface.wdn_loop_landing_association assoc_fx,
table(cast( v_CustomerLoop as Kroner.t_CustomerLoopElement)) input_loop
where loop_f1.CO_CLLI = v_CustomerLoop(1).co_clli
and loop_f1.LOOPID = assoc_f1.LOOPID
and assoc_f1.landing_NUMBER = v_CustomerLoop(1).landing_number
and assoc_f1.landing_ID = seg_f1.landing_ID
and seg_f1.CABLE = v_CustomerLoop(1).cable
and (seg_f1.low_coup <= v_CustomerLoop(1).coup and seg_f1.high_coup >= v_CustomerLoop(1).coup)
and seg_f1.TERMSYSID = v_CustomerLoop(1).termsysid
and assoc_f1.landing_number = 1
and loop_f1.loopid = assoc_fx.loopid
and assoc_fx.landing_ID = seg_fx.landing_id
and assoc_fx.landing_number = input_loop.landing_number
and seg_fx.CABLE = input_loop.cable
and (seg_fx.low_coup <= input_loop.coup and seg_fx.high_coup >= input_loop.coup)
and seg_fx.termsysid = input_loop.termsysid
group by loop_f1.loopid
having max(assoc_fx.landing_NUMBER) = :noOflandings
and count(case when assoc_fx.landing_number = input_loop.landing_number then 1 else 0 end) = :noOflandings';
EXECUTE IMMEDIATE v_sql INTO o_LoopId
USING v_CustomerLoop.count,v_CustomerLoop.count;Hi,
I don't know much about object types, but I think that the error is due to the usage of v_CustomerLoop variable in a different context.
Imagine that using the EXECUTE IMMEDIATE you spawn a different process that communicates with the caller using prameters (USING) and return values (INTO).
In this case, the variable is not visible by the new environement (it is not the same behaviour of nesting a BEGIN/END block in a procedure and referencing a parent variable)
Hope this helps
Max -
Anybody can help with this SQL?
The table is simple, only 2 columns:
create table personpay(
id integer primary key,
pay number(8,2) not null);
So the original talbe looks like this:
ID PAY
1 800
2 400
3 1200
4 500
5 600
6 1900
The requirement is to use one single query(no pl/sql) to show something lile the following, in other words, for each ID, the pay is the sum of all before itself and itself. So the query result looks like this:
ID PAY
1 800
2 1200
3 2400
4 2900
5 3500
6 5400
Again, just use one sql. No pl/sql. Anybody can help with this? I really appreciate that.
thanks,Eh, people are so "analytically minded" that can't even notice a simple join?
Counting Ordered Rows
Let’s start with a basic counting problem. Suppose we are given a list of integers, for example:
x
2
3
4
6
9
and want to enumerate all of them sequentially like this:
x #
2 1
3 2
4 3
6 4
9 5
Enumerating rows in the increasing order is the same as counting how many rows precede a given row.
SQL enjoys success unparalleled by any rival query language. Not the last reason for such popularity might be credited to its proximity to English . Let examine the informal idea
Enumerating rows in increasing order is counting how many rows precede a given row.
carefully. Perhaps the most important is that we referred to the rows in the source table twice: first, to a given row, second, to a preceding row. Therefore, we need to join our number list with itself (fig 1.1).
Cartesian Product
Surprisingly, not many basic SQL tutorials, which are so abundant on the web today, mention Cartesian product. Cartesian product is a join operator with no join condition
select A.*, B.* from A, B
Figure 1.1: Cartesian product of the set A = {2,3,4,6,9} by itself. Counting all the elements x that are no greater than y produces the sequence number of y in the set A.
Carrying over this idea into formal SQL query is straightforward. As it is our first query in this book, let’s do it step by step. The Cartesian product itself is
select t.x x, tt.x y
from T t, T tt
Next, the triangle area below the main diagonal is
select t.x x, tt.x y
from T t, T tt
where tt.x <= t.x
Finally, we need only one column – t.x – which we group the previous result by and count
select t.x, count(*) seqNum
from T t, T tt
where tt.x <= t.x
group by t.x
What if we modify the problem slightly and ask for a list of pairs where each number is coupled with its predecessor?
x predecessor
2
3 2
4 3
6 4
9 6
Let me provide a typical mathematician’s answer, first -- it is remarkable in a certain way. Given that we already know how to number list elements successively, it might be tempted to reduce the current problem to the previous one:
Enumerate all the numbers in the increasing order and match each sequence number seq# with predecessor seq#-1. Next!
This attitude is, undoubtedly, the most economical way of thinking, although not necessarily producing the most efficient SQL. Therefore, let’s revisit our original approach, as illustrated on fig 1.2.
Figure 1.2: Cartesian product of the set A = {2,3,4,6,9} by itself. The predecessor of y is the maximal number in a set of x that are less than y. There is no predecessor for y = 2.
This translates into the following SQL query
select t.x, max(tt.x) predecessor
from T t, T tt
where tt.x < t.x
group by t.x
Both solutions are expressed in standard SQL leveraging join and grouping with aggregation. Alternatively, instead of joining and grouping why don’t we calculate the count or max just in place as a correlated scalar subquery:
select t.x,
(select count(*) from T tt where tt.x <= t.x) seq#
from T t
group by t.x
The subquery always returns a single value; this is why it is called scalar. The tt.x <= t.x predicate connects it to the outer query; this is why it is called correlated. Arguably, leveraging correlated scalar subqueries is one the most intuitive techniques to write SQL queries.
How about counting rows that are not necessarily distinct? This is where our method breaks. It is challenging to distinguish duplicate rows by purely logical means, so that various less “pure” counting methods were devised. They all, however, require extending the SQL syntactically, which was the beginning of slipping along the ever increasing language complexity slope.
Here is how analytic SQL extension counts rows
select x, rank() over(order by x) seq# from T; -- first problem
select x, lag() over(order by x) seq# from T; -- second problem
Many people suggest that it’s not only more efficient, but more intuitive. The idea that “analytics rocks” can be challenged in many ways. The syntactic clarity has its cost: SQL programmer has to remember (or, at least, lookup) the list of analytic functions. The performance argument is not evident, since non-analytical queries are simpler construction from optimizer perspective. A shorter list of physical execution operators implies fewer query transformation rules, and less dramatic combinatorial explosion of the optimizer search space.
It might even be argued that the syntax could be better. The partition by and order by clauses have similar functionality to the group by and order by clauses in the main query block. Yet one name was reused, and the other had been chosen to have a new name. Unlike other scalar expressions, which can be placed anywhere in SQL query where scalar values are accepted, the analytics clause lives in the scope of the select clause only. I have never been able to suppress an impression that analytic extension could be designed in more natural way. -
Can anybody see what is wrong with this SQL statement?
Hey guys, just a quick question. Can anybody tell me what is wrong with this line of SQL? I keep getting a syntax error message. I've been trying for ages and I can't see any problem at all!"
{code}prepStat = connection.prepareStatement("INSERT INTO WeatherHistory (Date, Location, Overview, Temperature, WindDirection, WindSpeed, Pressure) VALUES ('"+date+"','"+location+"','"+temp+"','"+windDir+"','"+windSpd+"','"+pressure+"')");{code}
All the field names and variables definitely exist so I can't see what the problem is!DHD wrote:
Thanks for the replies.
I've matched the correct number of column names and variables, but still no luck.
And how exactly am I misusing Prepared Statements here?As noted above, not according to the code you posted. I didn't just pluck something out of my @ss and throw it out there. There was a reason behind what I said. And, if you mean you changed it, and you still got an exception, then post that exception (completely), and your new code, which is, hopefully, using PreparedStatement, (properly). -
Please help me with this SQL query
I am practicing SQL queries and have come across one involving fetching data from 3 different tables.
The three tables are as below
<pre>
Country
location_id country
loc1 Spain
loc2 England
loc3 Spain
loc4 USA
loc5 Italy
loc6 USA
loc7 USA
</pre>
<pre>
User
user_id location_id
u1 loc1
u2 loc1
u3 loc2
u4 loc2
u5 loc1
u6 loc3
</pre>
<pre>
Post
post_id user_id
p1 u1
p2 u1
p3 u2
p4 u3
p5 u1
p6 u2
</pre>
I am trying to write an SQL query - for each country of users, display the average number of posts
I understand the logic behind this that we first need to group together all the locations and then the users belonging to one country and then find the average of their posts.
But, i'm having a difficulty in putting this in SQL form. Could someone please help me with this query.
Thanks.select
country.country,
count(*) Totalpostspercountry,
count(distinct post.user_id) Totaldistincuserspercountry,
count(*)/count(distinct post.user_id) Avgpostsperuserbycountry
from
country, muser, post
where country.location_id = muser.location_id
and muser.user_id = post.user_id
group by country.country
The output is like this for your sample data - hope this is what you were looking for :)
COUNTRY,TOTALPOSTSPERCOUNTRY,TOTALDISTINCUSERSPERCOUNTRY,AVGPOSTSPERUSERBYCOUNTRY
England,1,1,1,
Spain,5,2,2.5, -
What wrong with this sql ?
what wrong with my sql ?? When i try to run a explain plain against it. I get it that perfectly fine...if the syntax was wrong i wont get the explain plan, then why am i getting invalid number error ??? is it the data ?? i am on 10.2.0.3
Edited by: S2K on Aug 18, 2009 10:21 AMS2K wrote:
i am sorry i am not able to get what you mean...do you mean i should have it something like this ??
CASE WHEN tv.var_data_typ_nm = 'Continuous' THEN ROUND(cr.rslt_qty, tmc.rpt_prcsn)
ELSE cr.rslt_qty END,
Well, I did not realize column with QTY in the name is stored as string. Then your issue is values stored in cr.rslt_qty - at least one is not numeric. Keep in mind balnk string will fail:
SQL> select round(' ') from dual
2 /
select round(' ') from dual
ERROR at line 1:
ORA-01722: invalid number
SQL> So if you can have blank cr.rslt_qty use LTRIM/RTRIM.
SY. -
Help, been fighting with this sql for a day now
Grateful if someone could give me a pointer here. fighting with this thing for a day and cannot get it right.
Have 2 tables
tbl_ate_jun & tbl_pd_jun
both xt tables
here are the creates for each.
CREATE TABLE "ME"."TBL_PD_JUN"
"ID" VARCHAR2(500 BYTE),
"PROJECT_NUMBER" VARCHAR2(500 BYTE),
"PROJECT_NAME" VARCHAR2(500 BYTE),
"DESCRIPTION" VARCHAR2(500 BYTE),
"PROJECT_TYPE" VARCHAR2(500 BYTE),
"ORGANIZATIONAL_NAME" VARCHAR2(500 BYTE),
"CUSTOMER_NAME" VARCHAR2(500 BYTE),
"OFFICE_FSR" VARCHAR2(500 BYTE),
"PROGRAMS_FSR" VARCHAR2(500 BYTE)
ORGANIZATION EXTERNAL
TYPE ORACLE_LOADER DEFAULT DIRECTORY "XE_FTP" ACCESS PARAMETERS ( records delimited BY newline skip 0 fields terminated BY ',' OPTIONALLY ENCLOSED BY '"' MISSING FIELD VALUES ARE NULL ) LOCATION ( 'tbl_pd_jun.csv' )
CREATE TABLE "ME"."TBL_ATE_JUN"
"ID" VARCHAR2(500 BYTE),
"PERSON_SSO" VARCHAR2(500 BYTE),
"FIRST_NAME" VARCHAR2(500 BYTE),
"LAST_NAME" VARCHAR2(500 BYTE),
"VOUCHER_HOURS" VARCHAR2(500 BYTE),
"FISCAL_YEAR_WEEK" VARCHAR2(500 BYTE),
"ORG_TIER2_NAME" VARCHAR2(500 BYTE),
"ORG_TIER3_NAME" VARCHAR2(500 BYTE),
"VOUCHER_REASON" VARCHAR2(500 BYTE),
"VOUCHERING_STATUS" VARCHAR2(500 BYTE),
"ORG_TIER4_NAME" VARCHAR2(500 BYTE),
"TIER4_MANAGER_NAME" VARCHAR2(500 BYTE),
"VOUCHER_CODE" VARCHAR2(500 BYTE),
"VOUCHER_DESCRIPTION" VARCHAR2(500 BYTE),
"PERSON_COUNT" VARCHAR2(500 BYTE),
"HOUR_TYPE" VARCHAR2(500 BYTE),
"APPLIED_FLAG" VARCHAR2(500 BYTE),
"COST_CENTER_CODE" VARCHAR2(500 BYTE),
"VOUCHER_CLASS" VARCHAR2(500 BYTE),
"VOUCHER_CLASS_DESCRIPTION" VARCHAR2(500 BYTE),
"VOUCHER_SUB_CLASS" VARCHAR2(500 BYTE),
"PROGRAM_TYPE" VARCHAR2(500 BYTE),
"PAYCODE_NAME" VARCHAR2(500 BYTE),
"PAY_CODE" VARCHAR2(500 BYTE)
ORGANIZATION EXTERNAL
TYPE ORACLE_LOADER DEFAULT DIRECTORY "XE_FTP" ACCESS PARAMETERS ( records delimited BY newline skip 0 fields terminated BY ',' OPTIONALLY ENCLOSED BY '"' MISSING FIELD VALUES ARE NULL ) LOCATION ( 'tbl_ate_jun.csv' )
) ;basically in tbl_ate_jun it has all the user ids (person_sso)
Im trying to generate a report that has all person_sso numbers in first column.
Second column have applied_hours, then office_hours, then programs_hours, then total_hours, then diff_hours (difference).
here is the code so far but i just cant get it right, it never shows all sso's, each select individually works fine, but cant combine, doesnt work right.
select a.person_sso,NVL(sum(b.applied_hours),0),NVL(sum(c.office_hours),0),NVL(sum(d.programs_hours),0),NVL(sum(e.total_hours),0),NVL(sum(f.diff_hours),0)
from
tbl_ate_jun a,
(SELECT
tbl_ate_jun.person_sso as applied_sso,
tbl_ate_jun.Voucher_Hours as applied_hours
FROM
tbl_pd_jun,
tbl_ate_jun
WHERE
tbl_ate_jun.voucher_code IN (select project_number from tbl_pd_jun
where Office_FSR IS NULL AND Programs_FSR IS NULL)
and tbl_ate_jun.voucher_code=tbl_pd_jun.project_number
)b,
(SELECT
tbl_ate_jun.person_sso as office_sso,
tbl_ate_jun.Voucher_Hours as office_hours
FROM
tbl_pd_jun,
tbl_ate_jun
WHERE
tbl_pd_jun.Project_Number=tbl_ate_jun.Voucher_Code AND tbl_pd_jun.Office_FSR = 'Y'
)c,
(SELECT
tbl_ate_jun.person_sso as programs_sso,
tbl_ate_jun.Voucher_Hours as programs_hours
FROM
tbl_pd_jun,
tbl_ate_jun
WHERE
tbl_pd_jun.Project_Number=tbl_ate_jun.Voucher_Code AND tbl_pd_jun.Programs_FSR = 'Y'
)d,
(SELECT
tbl_ate_jun.person_sso as total_sso,
tbl_ate_jun.Voucher_Hours as total_hours
from
tbl_ate_jun
)e,
(SELECT
tbl_ate_jun.person_sso as diff_sso,
tbl_ate_jun.Voucher_Hours as diff_hours
from
tbl_ate_jun
WHERE voucher_code NOT IN (select project_number from tbl_pd_jun)
)f
where
a.person_sso=b.applied_sso
and a.person_sso=c.office_sso
and a.person_sso=d.programs_sso
and a.person_sso=e.total_sso
and a.person_sso=f.diff_sso
group by a.person_ssoplease help. not every column will be populated with a sum of data, some would be empty if it didnt apply to that sso.
Edited by: Jay on Aug 10, 2011 7:45 AMI think an outer join will work so im not going to post all the sample data.
Can someone help with the syntax ? so i want to join all selects with a full outer join. i tried like this with 2 of them
select a.person_sso,b.applied_sso,b.applied_hours from
(tbl_ate_jun) a
full outer join
(SELECT
tbl_ate_jun.person_sso as applied_sso,
sum(tbl_ate_jun.Voucher_Hours) as applied_hours
FROM
tbl_pd_jun,
tbl_ate_jun
WHERE
tbl_ate_jun.voucher_code IN (select project_number from tbl_pd_jun
where Office_FSR IS NULL AND Programs_FSR IS NULL)
and tbl_ate_jun.voucher_code=tbl_pd_jun.project_number
group by tbl_ate_jun.person_sso)b on a.person_sso = b.applied_sso
but I get an error "No more data to read from socket"
Maybe you are looking for
-
Openoffice stopped working after pacman -Syu
I ran an update this morning, and now my Openoffice won't run. The update included: [12/07/04 10:08] upgraded glibc (2.3.3-2 -> 2.3.4-1) [12/07/04 10:08] upgraded wput (0.4-1 -> 0.5-1) So I am guessing that the new glibc is the cause. Trying to run O
-
I received a pop up about virus screening for my computer while on line. It displayed the Mac logo ,so I went ahead and aloowed it to scan for "virus" It isaid I was infected and I could purchase a clean up service by registeringing and paying 39 bu
-
I'm the assistant editor on a feature thats being cut on FCP HD Studio and I've hit a problem with the EDL. The film was transferred from 35mm to BETA and then to DVCAM and I logged everything with 24fps capture settings and have been editing on a 24
-
Error while using SAP Logon PAD
Hii, This is not an ABAP related doubt but a general one. I am getting an error 'The Procedure entry point RfcResetTraceDir could not be located in the dynamic link library LIBRFC32.dll. when am clicking on sap logon pad. Does anyone knw y this error
-
Flash Player 8 Won't Install On My Mac
I find Flash Player, version 8.0 to be rather difficult to open on my computer. Simply put, my computer is a PowerMac 4,2 (OS system is 10.4.6) that has a 2.0.3 version of the web browser Safari on it (plus over 4 GB of memory leftover) and it refuse