Unable to understand Connect by with this SQL
I have to generate a sequence like this for a record based on the count. For eg., E1 has a value 4, then the SQL below
with tmp as
select 'E1' as emp, 4 as cnt from dual
SELECT emp, LEVEL rn
FROM tmp
CONNECT BY LEVEL < cnt + 1 ;
produces 4 records
E1,1
E2,1
E3,1
E4,1
But, when I have another record E2 also as shown below
with tmp as
select 'E1' as emp, 4 as cnt from dual
union
select 'E2' as emp, 4 as cnt from dual
SELECT emp, LEVEL rn
FROM tmp
CONNECT BY LEVEL < cnt + 1 ;
it produces 30 records. I was expecting only 8. I had to put a distinct to avoid it. So, can I generate 4 for each E1,E2 without using distinct.
The actual table that I have is a huge table and so trying to avoid distinct. Thanks.
Satish
Hi, Satish,
user572405 wrote:
I have to generate a sequence like this for a record based on the count. For eg., E1 has a value 4, then the SQL below
with tmp as
select 'E1' as emp, 4 as cnt from dual
SELECT emp, LEVEL rn
FROM tmp
CONNECT BY LEVEL < cnt + 1 ;
produces 4 records
E1,1
E2,1
E3,1
E4,1Really?
When I run that, I get this output:
EM RN
E1 1
E1 2
E1 3
E1 4
But, when I have another record E2 also as shown below
with tmp as
select 'E1' as emp, 4 as cnt from dual
union
select 'E2' as emp, 4 as cnt from dual
SELECT emp, LEVEL rn
FROM tmp
CONNECT BY LEVEL < cnt + 1 ;
it produces 30 records. I was expecting only 8. I had to put a distinct to avoid it. So, can I generate 4 for each E1,E2 without using distinct.
The actual table that I have is a huge table and so trying to avoid distinct. Thanks."CONNECT BY LEVEL < x" (with no other conditions) should only be used on one-row tables, like dual.
Perhaps you need to join such a result set to another table (or result set), like this:
WITH emps AS
SELECT 'E1' AS emp, 4 AS cnt FROM dual
UNION ALL
SELECT 'E2' AS emp, 4 AS cnt FROM dual
, cntr AS
SELECT LEVEL AS rn
FROM dual
CONNECT BY LEVEL <=
SELECT MAX (cnt)
FROM emps
SELECT emp
, rn
FROM emps
JOIN cntr ON cntr.rn <= emps.cnt
;which produces:
EM RN
E1 1
E2 1
E1 2
E2 2
E1 3
E2 3
E1 4
E2 4Edited by: Frank Kulash on Dec 31, 2008 3:44 PM
Similar Messages
-
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) -
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. -
ODBC Gateway on Linux error - connects ok with Sybase SQL Anywhere
OS: CentOS 5.8 64-bit
DB: Oracle XE 11gR1 64-bit
Gateway: Oracle Gateway for ODBC 64-bit
Database and gateway reside on same Linux Server.
Connecting to remote Sybase SQL Anywhere 10 server on WindowsXP.
Using SQL Anywhere 11 odbc driver and unixODBC driver manager on Linux server.
isql tool connects without any problems.
One LISTENER, service for db and gateway on same port.
===================================
Via SQL*Plus, the following error occurs....
SQL> select * from dual@dblink;
select * from dual@dblink
ERROR at line 1:
ORA-28513: internal error in heterogeneous remote agent
ORA-02063: preceding line from dblink
===================================
sqlnet.ora
# sqlnet.ora Network Configuration File: /u01/app/oracle/product/11.2.0/xe/network/admin/sqlnet.ora
# Generated by Oracle configuration tools.
NAMES.DIRECTORY_PATH=(TNSNAMES)
ADR_BASE = /u01/app/oracle/product/11.2.0/xe
==================================
tnsnames.ora
# tnsnames.ora Network Configuration File:
XE =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = mysystem)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = XE)
dblink =
(DESCRIPTION =
(ADDRESS =
(PROTOCOL = TCP)(HOST = mysystem)(PORT = 1521)
(CONNECT_DATA =
(SID = dblink))
(HS=OK))
EXTPROC_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
(CONNECT_DATA =
(SID = PLSExtProc)
(PRESENTATION = RO)
=======================
listener.ora
# listener.ora Network Configuration File:
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = /u01/app/oracle/product/11.2.0/xe)
(PROGRAM = extproc)
(SID_DESC =
(SID_NAME = dblink)
(ORACLE_HOME = /u01/app/oracle/product/11.2.0/gtw)
(PROGRAM = dg4odbc)
(ENVS=LD_LIBRARY_PATH=/opt/sqlanywhere11/lib64:/u01/app/oracle/product/11.2.0/gtw/lib)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
(ADDRESS = (PROTOCOL = TCP)(HOST = mysystem)(PORT = 1521))
DEFAULT_SERVICE_LISTENER = (XE)
========================
initdblink.ora
# This is a sample agent init file that contains the HS parameters that are
# needed for the Database Gateway for ODBC
# HS init parameters
HS_FDS_CONNECT_INFO=dblink
HS_FDS_SHAREABLE_NAME=/usr/lib64/libodbc.so
HS_FDS_TRACE_LEVEL=255
HS_LANGUAGE=american_america.we8iso8859p1
HS_NLS_NCHAR=UTF-8
# ODBC specific environment variables
set ODBCINI=/etc/odbc.ini
========================
Oracle Corporation --- MONDAY OCT 15 2012 17:23:39.915
Heterogeneous Agent Release
11.2.0.1.0
Oracle Corporation --- MONDAY OCT 15 2012 17:23:39.914
Version 11.2.0.1.0
Entered hgogprd
HOSGIP for "HS_FDS_TRACE_LEVEL" returned "255"
Entered hgosdip
setting HS_OPEN_CURSORS to default of 50
setting HS_FDS_RECOVERY_ACCOUNT to default of "RECOVER"
setting HS_FDS_RECOVERY_PWD to default value
setting HS_FDS_TRANSACTION_LOG to default of HS_TRANSACTION_LOG
setting HS_IDLE_TIMEOUT to default of 0
setting HS_FDS_TRANSACTION_ISOLATION to default of "READ_COMMITTED"
HOSGIP returned value of "UTF-8" for HS_NLS_NCHAR
setting HS_FDS_TIMESTAMP_MAPPING to default of "DATE"
setting HS_FDS_DATE_MAPPING to default of "DATE"
setting HS_RPC_FETCH_REBLOCKING to default of "ON"
setting HS_FDS_FETCH_ROWS to default of "100"
setting HS_FDS_RESULTSET_SUPPORT to default of "FALSE"
setting HS_FDS_RSET_RETURN_ROWCOUNT to default of "FALSE"
setting HS_FDS_PROC_IS_FUNC to default of "FALSE"
setting HS_FDS_CHARACTER_SEMANTICS to default of "FALSE"
setting HS_FDS_MAP_NCHAR to default of "TRUE"
setting HS_NLS_DATE_FORMAT to default of "YYYY-MM-DD HH24:MI:SS"
setting HS_FDS_REPORT_REAL_AS_DOUBLE to default of "FALSE"
setting HS_LONG_PIECE_TRANSFER_SIZE to default of "65536"
setting HS_SQL_HANDLE_STMT_REUSE to default of "FALSE"
setting HS_FDS_QUERY_DRIVER to default of "TRUE"
setting HS_FDS_SUPPORT_STATISTICS to default of "FALSE"
Parameter HS_FDS_QUOTE_IDENTIFIER is not set
setting HS_KEEP_REMOTE_COLUMN_SIZE to default of "OFF"
setting HS_FDS_GRAPHIC_TO_MBCS to default of "FALSE"
setting HS_FDS_MBCS_TO_GRAPHIC to default of "FALSE"
Default value of 64 assumed for HS_FDS_SQLLEN_INTERPRETATION
setting HS_CALL_NAME_ISP to "gtw$:SQLTables;gtw$:SQLColumns;gtw$:SQLPrimaryKeys;gtw$:SQLForeignKeys;gtw$:SQLProcedures;gtw$:SQLStatistics;gtw$:SQLGetInfo"
setting HS_FDS_DELAYED_OPEN to default of "TRUE"
setting HS_FDS_WORKAROUNDS to default of "0"
Exiting hgosdip, rc=0
ORACLE_SID is "dblink"
Product-Info:
Port Rls/Upd:1/0 PrdStat:0
Agent:Oracle Database Gateway for ODBC
Facility:hsa
Class:ODBC, ClassVsn:11.2.0.1.0_0008, Instance:dblink
Exiting hgogprd, rc=0
hostmstr: 0: HOA After hoagprd
Invalid HS_NLS_NCHAR value UTF-8 specified
Setting HS_NLS_NCHAR to Server Default 2000
Invalid HS_NLS_NCHAR value UTF-8 specified
Setting HS_NLS_NCHAR to Server Default 2000
hostmstr: 0: HOA Before hoainit
Entered hgoinit
HOCXU_COMP_CSET=1
HOCXU_DRV_CSET=31
HOCXU_DRV_NCHAR=2000
HOCXU_DB_CSET=873
HOCXU_SEM_VER=112000
Exiting hgoinit, rc=28513
hostmstr: 0: HOA After hoainit
RPC Calling nscontrol(0), rc=0
hostmstr: 0: RPC Before Exit Agent
hostmstr: 0: HOA Before hoaexit
Entered hgoexit
HS Gateway: NULL connection context at exit
Exiting hgoexit, rc=0 with error ptr FILE:hgoexit.c LINE:108 FUNCTION:hgoexit() ID:Connection context
hostmstr: 0: HOA After hoaexit
hostmstr: 0: RPC After Exit Agent
=============================
Also, does anyone know how to determine the location (full path) of the unixODBC driver manager ?
Please assist if you can...thx.
Edited by: user601798 on Oct 15, 2012 3:37 PMLet me start with the unixODBC driver:
There's no generic location as it depends which package you've used to install the UnixODBC driver manager or how you compiled it from scratch. I commonly prefer to compile it from scratch as this offers me to install it to any location I like.
If you're not sure where it is located, you could perform a search on your machine looking for libodbc.so. Then cross check it with "file <location>/libodbc.so" to see the lib is a 64bit library.
So let's assume in the /usr/lib64 you found the libodbc.so library, then the setting
HS_FDS_SHAREABLE_NAME=/usr/lib64/libodbc.so
is correct. Else you need to adopt the parameter.
Next step is to check out which unixODBC version is installed. That's commonly done by calling "odbcinst -j".
Looking now ta the gateway init file there's a parameter HS_NLS_NCHAR set to UTF-8. UnixODBC is commonly compiled with UCS2 support, so please change it to HS_NLS_NCHAR=UCS2
Could you also please post the content of the odbc.ini file "more /etc/odbc.ini"?
Thanks,
Klaus -
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 PMSolution
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 -
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, -
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. -
HT201485 Ihave an apple id . I am unable to access itunes stores with this id
I have an apple id but unable to access i tunes store with this & password for purchases
Click on the AppStore application on iPhone. Click FEATURED. Scroll to the bottom of the screen. Click on your AppleID. In the Menu sign out then sign back in.
If this doesnt work, repeat the above; when you get to the menu after clicking on your appleID in the app store click, VIEW APPLE ID. Once you do that you should be able to change the store in the country/region settings. -
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" -
Error connecting jsp with MS SQL Server 2000
Dear all,
I have developed a simple application in java for connecting with SQL Server. But the same thing is not working in jsp. We are using Tomcat 4.0 as a server. Which jar files am I supposed to keep in the Tomcat folder and plz, give the entire path.There are three msbase.jar, msutil.jar and mssqlserver.jar. Put these in the /WEB-INF/lib directory of your application OR... if you will be writing multiple applications that use this, you can put them in the <%TOMCAT_HOME%>/common/lib directory.
From there it should all be the same. -
What's wrong with this SQL Statement?
I hope somebody can help explain to me what is wrong wiht the
following SQL statement in my Recordest. It does not return an
error, but it will only filter records from the first variable
listed, 'varFirstName%'. If I try to use any other variables on my
search form,for example LastName, it returns all records. Why is it
doing this?
Here is the SQL statement:
SELECT *
FROM [Sysco Food Show Contacts]
WHERE FirstName LIKE 'varFirstName%' AND LastName LIKE
'varLastName%' AND OrganizationName LIKE 'varOrganizationName%' AND
Address LIKE 'varAddress%' AND City LIKE 'varCity%' AND State LIKE
'varState' AND PostalCode LIKE 'varPostalCode%'
The variables are defined as below:
Name Default Value Run-Time Value
varFirstName % Request.Form("FirstName")
varLastName % Request.Form("LastName")
...and such with all variables defined the same way.
Any help would be much appreciated. I am pulling my hair out
trying to make this Search Form work.
Thanks, mparsons2000PLEASE IGONRE THIS QUESTION!
There was nothing wrong with the statement. I had made
another STUDIP mistake! -
Code to connect jsp with MS SQL SERVER 2000
i have my SQL Server in my local machine and i need to conne ct my jsp page with that instance.
please provide a sample code to accomplish the same.
along with that can you please send me procedure to establish a DSN for SQL SERVER 2000.
thank you
with love
AnushhPrabuhttp://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSTL7.html
This is a good way of achieving what you want to do. But I should mention that the approach is suitable only for smaller applications. -
BI JDBC connection failure with MS SQL 2005 - but Portal JDBC is working
I am a portal novice.
I wanted to get tables in the visual composer. so i created the protal jdbc connection to MS SQL 2005. which is working fine.
Later i found i need BI jdbc for retreving tables from sql server. when i followed all the steps in the how to document, my connection test is failing. below is the log.
Test Details:
The test consists of the following steps:
1. Retrieve the default alias of the system
2. Check the connection to the backend application using the connector defined in this system object
Results
Retrieval of default alias successful
Connection failed. Make sure that Single Sign-On is configured correctly
can any help me there please.
- Points will he awarded for inputs.
thanks
-raviSwapnil,
Thanks for the reply, but the thread is completely different from what i am looking for.
can anybody throw some suggestion at my problem
-ravi
Maybe you are looking for
-
Can't Install Plugin in solaris 2.7 ( problem & solution )
Dear all, I have install Java Plug 1.2 for Solaris/sparc , os is solaris 2.7 and netscape is 4.75 . When start netscape, it shows following error message. ERROR: ld.so.1 :netscape: fatal: /opt/NSCPcom/j2pi//COPYRIGHT: unknown file type Cant load plug
-
HP DreamColor Advanced Profiling Solution discontinued problem
Hello All, i want to buy the HP DreamColor LP2480zx 24 for new video color correction project . after reading some comments on it i found that i have to buy the HP DreamColor Advanced Profiling Solution to maintain it is color and to be sure about t
-
Hi I am compiling a BPEL Process while compilation it is giving the following error, BPEL_XYZ.bpel", XML parsing failed because "". [Potential fix]: n/a. Can any body explain why these particular error occurs and solution for this Asap. Thanks in ada
-
Few battery cycles, but the battery breaks? surely a manufacturing fault
I experienced a situation where my battery needed replacing at only 131 cycles of usage, no where near the common level of 300 cycles, and I was covered with warranty, yet they insisted on me paying a fair bit for a new battery. It's ridiculous, I ha
-
Are SSRS reports suitable for making customizable reports?
Hi, I want to give users an option to make customize reports in my web application. So I need to confirm that SSRS reports are suitable for this option or something else I have to implement it. And if SSRS reports are suitable for this, then guide me