Subquery issue
SELECT m_label, (SELECT COUNT(c_id) FROM tbl_count WHERE tbl_main_fk = m_id) AS totalCount
FROM tbl_main
It's a simple subquery code to get the total count of the related table, and the result return perfectly when I click test, but it will fail in control panel, how to solve the problem?
It's definitely a bug in Dreamweaver. I have created a couple of tables using your structure, and it works fine in both phpMyAdmin and the Test panel of the Recordset dialog box. However, it triggers a MySQL error in the Bindings panel.
I have done some testing, and discovered that the query is being corrupted somehow. What is actually being submitted to the database by the Bindings panel is this:
SELECT a.*, (SELECT p.p_img FROM tbl_photos p
WHERE 0 = 1
I also tried your query without the table aliases like this:
SELECT tbl_album.*, (SELECT p_img FROM tbl_photos
WHERE tbl_album_fk = tbl_album.a_id AND p_cover = 1 LIMIT 0, 1)
AS coverImg FROM tbl_album
This resulted in the same problem:
SELECT tbl_album.*, (SELECT p_img FROM tbl_photos
WHERE 0 = 1
So, for some reason, it's being truncated after the table name in the subquery. I have no idea why.
I'm in touch with Dreamweaver engineers, and will raise this issue with them, but I doubt if there will be a rapid solution to this problem.
Similar Messages
-
Inner Subquery Issue....
Hi All,
I have a query as under:
Select calendar_date, man_days_demand
from (
select calendar_date,
( --Man_days_demand calculation
select count(fsr)
from t1,t2,t3,(select region_id from t4
union
select region_id from t3 ) TAB1
where tab1.region_id = '®ion_id'
) Man_days_demand
from calendar_fiscal_viewI am facing the problem with TAB1 inner subquery. the region that i am getting from TAB1 is compared to input of region_id but it is not working. It may be because inner subquery is executed first and hence any region i am inputting is not getting compared to region_id extracted from TAB1..
can anybody suggest alternate query or resolution to thsi issue as i need to compare the region coming from TAB1 to my input region.
Thanks,
JPHi,
I am posting my actual query:
SELECT calendar_date timeperiod,
man_days_demand demand
FROM (
SELECT cal.calendar_date calendar_date,
(-- in line column qry to count the service reqs falling on that specific day
-- DEMAND
SELECT decode(nvl(sum(count(ssrj.field_service_rep)),0),0,0,1)
FROM sop_service_request_job ssrj, sop_service_request ssr,
sop_service_user ssu, sop_user_map smp1 /*(\*select distinct region_id, ssu.sso_id sso_id
from sop_user_map smp,sop_service_user ssu
where smp.sso_id = ssu.sso_id and role_id = 1 *\
select region_id, sso_id
from sop_user_map smp
where role_id = 1
and upper(nvl(smp.region_id, 'test')) like
upper(nvl('%®ion_id%', 'test'))
union
select region_id, to_number(field_service_rep)
from sop_service_request_job ssrj, sop_service_request ssr
where ssr.service_request_id = ssrj.service_request_id
and field_service_rep is not null
and region_id is not null
and region_id != '~'
and upper(nvl(ssr.region_id, 'test')) like
upper(nvl('%®ion_id%', 'test'))
\*and ssrj.job_status = 'ASSIGNED'*\
and ssr.workflow_status in ('SUBMITTED','APPROVED','PARTIAL ASSIGNMENT','ASSIGNED','PENDING REVIEW','CLOSED')
) tab1*/
WHERE (((cal.calendar_date between ssrj.scheduled_start_date AND
get_end_date(ssrj.scheduled_start_date,
ssrj.expected_service_hours,
ssrj.weekend)))
OR
(cal.calendar_date < ssrj.scheduled_start_date and
cal.calendar_date > get_end_date(ssrj.scheduled_start_date,
ssrj.expected_service_hours,
ssrj.weekend)))
and ssrj.service_request_id = ssr.service_request_id
and smp1.sso_id = ssu.sso_id
and smp1.sso_id = ssrj.field_service_rep
and ssrj.field_service_rep is not null
/*and ssrj.job_status = 'ASSIGNED'*/
and ssr.workflow_status in ('SUBMITTED','APPROVED','PARTIAL ASSIGNMENT','ASSIGNED','PENDING REVIEW','CLOSED')
and ssu.sso_id = ssrj.field_service_rep
and nvl(ssu.sso_id,0) like nvl('%&ssoid%',0)
--and ssu.sso_id = tab1.sso_id
and smp1.region_id in (
select region_id
from sop_user_map smp
where role_id = 1
and upper(nvl(smp.region_id, 'test')) like
upper(nvl('%®ion_id%', 'test'))
union
select region_id
from sop_service_request_job ssrj, sop_service_request ssr
where ssr.service_request_id = ssrj.service_request_id
and field_service_rep is not null
and region_id is not null
and region_id != '~'
and upper(nvl(ssr.region_id, 'test')) like
upper(nvl('%®ion_id%', 'test'))
--and ssrj.job_status = 'ASSIGNED'
and ssr.workflow_status in ('SUBMITTED','APPROVED','PARTIAL ASSIGNMENT','ASSIGNED','PENDING REVIEW','CLOSED')
and upper(nvl(ssu.qualification,'test')) like upper(nvl('%&qualification%','test'))
and upper(nvl(ssr.platform_type,'test')) like upper(nvl('%&platform_name%','test'))
and upper(nvl(ssu.country,'test')) like upper(nvl('%&country%','test'))
--and upper(nvl(tab1.region_id,'test')) like upper(nvl('%®ion_id%','test'))
-- and upper(nvl(tab1.region_id,'test')) like upper(nvl('%®ion_id%','test'))
and upper(nvl(ssrj.weekend,'test')) like upper(nvl('%&weekend%','test'))
and upper(nvl(ssu.state,'test')) like upper(nvl('%&state%','test'))
GROUP BY calendar_date
) Man_Days_demand
from sop_fiscal_calendar_v cal
WHERE
calendar_date BETWEEN trunc(to_date('&date_range_start_date','mm/dd/yyyy'))
AND trunc(to_date('&date_range_end_date','mm/dd/yyyy'))
)This is also not working.. I need to filter by region...
Thanks,
JP -
the following sample is from ORACLE DATABASE 10g SQL
i don't understand how it works, the bellow is the table and the query
SELECT Product_id pid, product_type_id ptid, name, price
FROM products
PID PTID NAME PRICE
1 1 Modern Science 19.95
2 1 Chemistry 30
3 2 Supernova 25.99
4 2 Tank War 13.95
5 2 Z Files 49.99
6 2 2412: The Return 14.95
7 3 Space Force 9 13.49
8 3 From Another Planet 12.99
9 4 Classical Music 10.99
10 4 Pop 3 15.99
11 4 Creative Yell 14.99
PID PTID NAME PRICE
12 My Front Line 13.49
the query
SELECT product_id pid, product_type_id ptid, name, price
FROM products outer
WHERE price >
(SELECT AVG(price)
FROM products inner
WHERE inner.product_type_id = outer.product_type_id)
PID PTID NAME PRICE
2 1 Chemistry 30
5 2 Z Files 49.99
7 3 Space Force 9 13.49
10 4 Pop 3 15.99
11 4 Creative Yell 14.99
what i don't understand is HOW and WHEN the AVG function works and HOW AVG() function knows to calculate the average by grouping the PTID not the average of ALL PRICE column.
tks for helping in advanceThe subquery
(SELECT AVG(price)
FROM products inner
WHERE inner.product_type_id = outer.product_type_id)knows to create an average of all the products with the same product type because of the WHERE clause, which limits the rows returned to those with the product_type_id in the outer.
Conceptually, what happens is
- the outer query gets the first row of the table (PID=1)
- it grabs the price (19.95)
- now, it runs the subquery to determine whether this is above average
- the subquery sees that outer.product_type_id is 1, so the WHERE clause eliminates all but the first two rows (PID 1&2). The average of 19.95 and 30 is 24.975.
- Since the price of the first row is not greater than 24.975, Oracle knows that it does not meet the conditions of the WHERE clause in the outer query.
- Repeat for each row in the outer query
Obviously, since Oracle is doing set-based processing, it may not work exactly this way internally. Conceptually, though, this is how correlated subqueries work.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
SQL Aggregate function and Subquery issues
Hello,
I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
With T1 As(
SELECT
b."etat",
c."secteur",
d.annee_fiscale_full,
d.periode,
SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES
FROM vsRequete a,
vsEtats b,
vsOperation c,
periode_financiere d,
vstemps_operatoires e
WHERE b."etat" <> 'Cancelled'
AND (b."Cle_requete" = a."Cle_vsRequete")
AND (c."Cle_requete" = a."Cle_vsRequete")
AND (b."Cle_requete" = c."Cle_requete")
AND (a."Cle_vsRequete" = e."Cle_requete")
AND c."date_operation" = d.per_fina_date
GROUP BY
b."etat",
c."secteur",
--a."type_visite",
d.annee_fiscale_full,
d.periode )
SELECT
---- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
---- RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,
T1."secteur",
--a."type_visite",
T1.annee_fiscale_full,
T1.periode
FROM T1
Where T1."etat" = 'Urgent'
ORDER BY
T1.annee_fiscale_full,
T1.periode,
T1."secteur";
Thanks for your help
Edited by: Ruben_920841 on Dec 21, 2012 1:40 PM
Edited by: Ruben_920841 on Dec 21, 2012 1:41 PMHi,
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
Always say which version of Oracle you're using (for example, 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Ruben_920841 wrote:
Hello,
I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
With T1 As(
SELECT
b."etat",
c."secteur",
d.annee_fiscale_full,
d.periode,
SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES Is it possible, in a group of rows with the same "Cle_requete", for some rows to have "etate"='Urgent' and other rows to have some other value besides 'Cancelled'? If so, how is that counted? Include an example or two in your sample data and results.
FROM vsRequete a,
vsEtats b,
vsOperation c,
periode_financiere d,
vstemps_operatoires e
WHERE b."etat" <> 'Cancelled'This site doesn't like to display the <> inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
AND (b."Cle_requete" = a."Cle_vsRequete")
AND (c."Cle_requete" = a."Cle_vsRequete")
AND (b."Cle_requete" = c."Cle_requete")
AND (a."Cle_vsRequete" = e."Cle_requete")
AND c."date_operation" = d.per_fina_date
GROUP BY
b."etat",
c."secteur",
--a."type_visite",
d.annee_fiscale_full,
d.periode )
Select
----- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
------ RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,That depends on your data, and your desired results. Based on what you've said so far, I think not. It's more likely that you'll want to use a CASE expression to get a count of the 'Urgent' surgeries.
T1."secteur",
--a."type_visite",
T1.annee_fiscale_full,
T1.periode
FROM T1
Where T1."etat" = 'Urgent'
ORDER BY
T1.annee_fiscale_full,
T1.periode,
T1."secteur";The forum FAQ {message:id=9360002} explains how to use \ tags to preserve spacing when you post formatted text, such as your query.
It sounds like your problem is similar to this one:
"What percentage of the employees (not counting SALESMEN) in each department of the scott.emp table are CLERKS?"
Here's one way you might answer that:WITH got_cnts AS
SELECT deptno
, COUNT ( DISTINCT CASE
WHEN job = 'CLERK'
THEN ename
END
) AS clerk_cnt
, COUNT (DISTINCT ename) AS total_cnt
FROM scott.emp
WHERE job != 'SALESMAN'
GROUP BY deptno
SELECT deptno
, clerk_cnt
, total_cnt
, 100 * clerk_cnt
/ total_cnt AS clerk_pct
FROM got_cnts
ORDER BY deptno
Output:DEPTNO CLERK_CNT TOTAL_CNT CLERK_PCT
10 1 3 33.33
20 2 5 40.00
30 1 2 50.00 -
Report Issue - A subquery filter may not reference the current report
Hi,
I a, trying to create a drill down report - I am getting below error when I drill down from summary report to detail -
A subquery filter may not reference the current report (or contain a circular reference to any report).
Error Details
Error Codes: S6C66RYK:WIF3IYGO
Recursion limit exceeded in Xml Expression Visitor
The issue is I have a budget report which will drill down to display amount by each period -
Jan-10 Feb-10 Mar-10
1223 123 10
Now I am trying to display detail GL transactions by clicking the amount field.
This means summary report should pass period along with amount to display detail GL transactions.
Please help me to resolve this issue.
Thanks,
PoojakExplain exactly how you create your 2 reports.
The second one must have "is prompted" filters if you want it to use the values of the first one. -
Hi All,
Oracle v11.2.0.2
I have a SELECT query which executes in less than a second and selects few records.
Now, if I put this SELECT query in IN clause of a DELETE command, that takes ages (even when DELETE is done using its primary key).
See below query and execution plan.
Here is the SELECT query
SQL> SELECT ITEM_ID
2 FROM APP_OWNER.TABLE1
3 WHERE COLUMN1 = 'SomeValue1234'
4 OR (COLUMN1 LIKE 'SomeValue1234%'
5 AND REGEXP_LIKE (
6 COLUMN1,
7 '^SomeValue1234[A-Z]{3}[0-9]{5}$'
8 ));
ITEM_ID
74206192
1 row selected.
Elapsed: 00:00:40.87
Execution Plan
Plan hash value: 3153606419
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 2 | 38 | 7 (0)| 00:00:01 |
| 1 | CONCATENATION | | | | | |
|* 2 | INDEX RANGE SCAN | PK_TABLE1 | 1 | 19 | 4 (0)| 00:00:01 |
|* 3 | INDEX UNIQUE SCAN| PK_TABLE1 | 1 | 19 | 3 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("COLUMN1" LIKE 'SomeValue1234%')
filter("COLUMN1" LIKE 'SomeValue1234%' AND REGEXP_LIKE
("COLUMN1",'^SomeValue1234[A-Z]{3}[0-9]{5}$'))
3 - access("COLUMN1"='SomeValue1234')
filter(LNNVL("COLUMN1" LIKE 'SomeValue1234%') OR LNNVL(
REGEXP_LIKE ("COLUMN1",'^SomeValue1234[A-Z]{3}[0-9]{5}$')))
Statistics
0 recursive calls
0 db block gets
8 consistent gets
0 physical reads
0 redo size
348 bytes sent via SQL*Net to client
360 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processedNow see the DELETE command. ITEM_ID is the primary key for TABLE2
SQL> delete from TABLE2 where ITEM_ID in (
2 SELECT ITEM_ID
3 FROM APP_OWNER.TABLE1
4 WHERE COLUMN1 = 'SomeValue1234'
5 OR (COLUMN1 LIKE 'SomeValue1234%'
6 AND REGEXP_LIKE (
7 COLUMN1,
8 '^SomeValue1234[A-Z]{3}[0-9]{5}$'
9 ))
10 );
1 row deleted.
Elapsed: 00:02:12.98
Execution Plan
Plan hash value: 173781921
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | DELETE STATEMENT | | 4 | 228 | 63490 (2)| 00:12:42 |
| 1 | DELETE | TABLE2 | | | | |
| 2 | NESTED LOOPS | | 4 | 228 | 63490 (2)| 00:12:42 |
| 3 | SORT UNIQUE | | 1 | 19 | 63487 (2)| 00:12:42 |
|* 4 | INDEX FAST FULL SCAN| I_TABLE1_3 | 1 | 19 | 63487 (2)| 00:12:42 |
|* 5 | INDEX RANGE SCAN | PK_TABLE2 | 7 | 266 | 3 (0)| 00:00:01 |
Predicate Information (identified by operation id):
4 - filter("COLUMN1"='SomeValue1234' OR "COLUMN1" LIKE 'SomeValue1234%' AND
REGEXP_LIKE ("COLUMN1",'^SomeValue1234[A-Z]{3}[0-9]{5}$'))
5 - access("ITEM_ID"="ITEM_ID")
Statistics
1 recursive calls
5 db block gets
227145 consistent gets
167023 physical reads
752 redo size
765 bytes sent via SQL*Net to client
1255 bytes received via SQL*Net from client
4 SQL*Net roundtrips to/from client
3 sorts (memory)
0 sorts (disk)
1 rows processedWhat can be the issue here?
I tried NO_UNNEST hint, which made difference, but still the DELETE was taking around a minute (instead of 2 minutes), but that is way more than that sub-second response.
Thanks in advancerahulras wrote:
SQL> delete from TABLE2 where ITEM_ID in (
2 SELECT ITEM_ID
3 FROM APP_OWNER.TABLE1
4 WHERE COLUMN1 = 'SomeValue1234'
5 OR (COLUMN1 LIKE 'SomeValue1234%'
6 AND REGEXP_LIKE (
7 COLUMN1,
8 '^SomeValue1234[A-Z]{3}[0-9]{5}$'
9 ))
10 );
The optimizer will transform this delete statement into something like:
delete from table2 where rowid in (
select t2.rowid
from
table2 t2,
table1 t1
where
t1.itemid = t2.itemid
and (t1.column1 = etc.... )
)With the standalone subquery against t1 the optimizer has been a little clever with the concatenation operation, but it looks as if there is something about this transformed join that makes it impossible for the concatenation mechanism to be used. I'd also have to guess that something about the way the transformation has happened has made Oracle "lose" the PK index. As I said in another thread a few minutes ago, I don't usually look at 10053 trace files to solve optimizer problems - but this is the second one today where I'd start looking at the trace if it were my problem.
You could try rewriting the query in this explicit join and select rowid form - that way you could always force the optimizer into the right path through table1. It's probably also possible to hint the original to make the expected path appear, but since the thing you hint and the thing that Oracle optimises are so different it might turn out to be a little difficult. I'd suggest raising an SR with Oracle.
Regards
Jonathan Lewis -
Subquery Factoring -Performance Issue
Hi experts,
Oracle 10G
select
a.colums,
b.columns
from
( select
Colums
from
F ,
(select
columns
from
bigtable
where
<condition with recdate and modified date with timezone convertions Given as in end of this qury)
) a,
( select
Colums
from
tables,
(select
columns
from
bigtable
where
<condition with recdate and modified date with timezone convertions Given as in end of this qury)
) b
(TO_DATE(TO_CHAR(FROM_TZ(CAST(CF.RECDT as timestamp),'GMT') at time zone 'America/Chicago','YYYY-MM-DD
HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')
BETWEEN TO_DATE('01-JAN-2009 00:00:00','DD-MON-YYYY HH24:MI:SS') AND TO_DATE('08-JAN-2009 00:00:00', 'DD-MON-YYYY
HH24:MI:SS')) OR
(TO_DATE(TO_CHAR(FROM_TZ(CAST(CF.MODIFID_DT as timestamp),'GMT') at time zone 'America/Chicago','YYYY-MM-DD
HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')
BETWEEN TO_DATE('01-JAN-2009 00:00:00','DD-MON-YYYY HH24:MI:SS') AND TO_DATE('08-JAN-2009 00:00:00', 'DD-MON-YYYY
HH24:MI:SS'))
Recdt - indexed
Modifieddt - not iddexed
bigtable used many times in select to avoid Subquery factoring used (with select) but it increased cost as per explain plan in sqldevleoper please suggest me to increase performance
Lots of thanks,
Kalinganow the above query use as
with subfact as
( select
select
columns
from
bigtable
where
<condition with recdate and modified date
select
a.colums,
b.columns
from
( select
Colums
from
F ,
subfact
where condition
) a,
( select
Colums
from
tables,
subfact
where condition
) b
it is cost increased in nested loop in explain plan why? is thre any other detail required. -
I have a requirement.
I have a report which looks like this
Emp_No Salary(ordered_desc) fte Cumulative_fte(RSUM)
1 1000 1 1
2 500 0.3 1.3
3 250 0.2 1.5
now i have a value -- which is 1.4 --- so my requirement is that as the cumulative value lies between 1.3 and 1.5 so i need to get the salary which is 500. Here the cumulative has to be based on salary desc.
So i am putting a filter like cumulative less than or equal to 1.4.
when i create new analysis in which i am getting emp no and salary from this analysis and doing a min on salary -- which should ideally give me 500.
This logic should hold good but the issue is that when i create new analysis and build filters based on this analysis, the order by in the salary is not coming due to which this logic is not coming correctly.
Please do let me know how i can achieve this...Hi Krishna,
I have not digged into much details of it, but understand that if you get the order by fixed, your report is fixed. If it is, then how about having a rank(salary) and then sorting it ascending.
This would make sure that the salary is always ordered descending and your logic working too.
Hope this helps.
Thank you,
Dhar -
Hi all,
I have a quick question. I'm just testing out Subqueries in the Select portion of the query. Here's what I'm trying to do:
select count(rownum) cnt, count(rownum)/(select count(rownum) from tablex) pcnt
from tablex where contraintfield = constraint;
Basically, just getting a population percentage for a given constraint. I know there are other ways to do this, using a case statement for example, but I don't know why I'm getting a group by error in the query above. I'm asking for a group over the entire table. To make things more baffling, on a hunch I wrote the following query that works:
select count(rownum) cnt, count(rownum)/(select count(rownum) from tablex) pcnt
from tablex where contraintfield = constraint
group by 1;
When I try to explicitly group by the first field, it bombs (as it should - grouping by count(rownum) should not work).
select count(rownum) cnt, count(rownum)/(select count(rownum) from tablex) pcnt
from tablex where contraintfield = constraint
group by count(rownum);
Can anyone help me understand why Oracle does not like the first query but the second works?
Thanks,
RobSeems that 'group by' needs a column name and if you use a number it doesn't matter which number you use or how many numbers you use
And 'order by' allows 1 for first col, 2 for second and so on
Connected to Personal Oracle9i Release 9.2.0.1.0
SQL> desc tbl;
Name Type Nullable Default Comments
ID INTEGER Y
NAME VARCHAR2(50) Y
SQL> select * from tbl;
ID NAME
1 one
2 two
3 three
1 eleven
2 twenty
2 twelve
6 rows selected
SQL> SELECT COUNT(rownum),
2 COUNT(id) / (SELECT COUNT(NAME)
3 FROM tbl)
4 FROM tbl
5 WHERE id = 2;
ORA-00937: not a single-group group function
SQL> SELECT COUNT(rownum) cnt,
2 COUNT(id) / (SELECT COUNT(NAME)
3 FROM tbl) pcnt
4 FROM tbl
5 WHERE id = 2
6 GROUP BY 523.683;
CNT PCNT
3 0.5
SQL> SELECT COUNT(rownum),
2 COUNT(id) / (SELECT COUNT(NAME)
3 FROM tbl)
4 FROM tbl
5 WHERE id = 2
6 group by 1 , 2 , 3, 0.980;
COUNT(ROWNUM) COUNT(ID)/(SELECTCOUNT(NAME)FR
3 0.5
SQL> SELECT MAX(NAME),
2 id
3 FROM tbl
4 WHERE id > 1
5 GROUP BY id;
MAX(NAME) ID
two 2
three 3
SQL> SELECT MAX(NAME),
2 id
3 FROM tbl
4 WHERE id > 1
5 GROUP BY 2;
ORA-00979: not a GROUP BY expression
SQL> SELECT MAX(NAME),
2 id
3 FROM tbl
4 WHERE id > 1
5 GROUP BY id
6 ORDER BY 2 DESC;
MAX(NAME) ID
three 3
two 2
SQL> SELECT COUNT(rownum) cnt,
2 COUNT(id) / (SELECT COUNT(NAME)
3 FROM tbl),
4 power(COUNT(id),
5 3),
6 NAME
7 FROM tbl
8 WHERE id = 2
9 GROUP BY 4;
ORA-00979: not a GROUP BY expression
SQL> SELECT COUNT(rownum) cnt,
2 COUNT(id) / (SELECT COUNT(NAME)
3 FROM tbl),
4 power(COUNT(id),
5 3),
6 NAME
7 FROM tbl
8 WHERE id = 2
9 GROUP BY NAME;
CNT COUNT(ID)/(SELECTCOUNT(NAME)FR POWER(COUNT(ID),3) NAME
1 0.166666666666667 1 twelve
1 0.166666666666667 1 twenty
1 0.166666666666667 1 two
so I am likewise puzzled
Peter -
select *from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE 11.1.0.7.0 Production
TNS for Linux: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - ProductionSQL
DELETE FROM A
WHERE TR_STATUS IN ('C', 'R')
OR A.TAX_AUDIT_RECORD_ID IN ( SELECT B.TAX_AUDIT_RECORD_ID FROM B WHERE A.TAX_AUDIT_RECORD_ID = B.TAX_AUDIT_RECORD_ID);Current execution plan
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop | TQ |IN-OUT| PQ Distrib |
| 0 | DELETE STATEMENT | | 5639K| 123M| 14156 (1)| 00:02:50 | | | | | |
| 1 | PX COORDINATOR | | | | | | | | | | |
| 2 | PX SEND QC (RANDOM) | :TQ20002 | 5639K| 123M| 14156 (1)| 00:02:50 | | | Q2,02 | P->S | QC (RAND) |
| 3 | INDEX MAINTENANCE | A | | | | | | | Q2,02 | PCWP | |
| 4 | PX RECEIVE | | 5639K| 123M| 14156 (1)| 00:02:50 | | | Q2,02 | PCWP | |
| 5 | PX SEND RANGE | :TQ20001 | 5639K| 123M| 14156 (1)| 00:02:50 | | | Q2,01 | P->P | RANGE |
| 6 | DELETE | A | | | | | | | Q2,01 | PCWP | |
| 7 | BUFFER SORT | | | | | | | | Q2,01 | PCWC | |
| 8 | PX RECEIVE | | 5639K| 123M| 14156 (1)| 00:02:50 | | | Q2,01 | PCWP | |
| 9 | PX SEND HASH (BLOCK ADDRESS)| :TQ20000 | 5639K| 123M| 14156 (1)| 00:02:50 | | | | S->P | HASH (BLOCK|
|* 10 | FILTER | | | | | | | | | | |
| 11 | PX COORDINATOR | | | | | | | | | | |
| 12 | PX SEND QC (RANDOM) | :TQ10000 | 5639K| 123M| 14156 (1)| 00:02:50 | | | Q1,00 | P->S | QC (RAND) |
| 13 | PX BLOCK ITERATOR | | 5639K| 123M| 14156 (1)| 00:02:50 | 1 | 32 | Q1,00 | PCWC | |
| 14 | TABLE ACCESS FULL | B | 5639K| 123M| 14156 (1)| 00:02:50 | 1 | 32 | Q1,00 | PCWP | |
| 15 | PARTITION RANGE ALL | | 1 | 21 | 3 (0)| 00:00:01 | 1 | 8 | | | |
|* 16 | INDEX RANGE SCAN | PK_B | 1 | 21 | 3 (0)| 00:00:01 | 1 | 8 | | | |
Predicate Information (identified by operation id):
10 - filter("A"."TR_STATUS"='C' OR "A"."TR_STATUS"='R' OR EXISTS (SELECT 0 FROM "B" WHERE
"B"."TAX_AUDIT_RECORD_ID"=:B1))
16 - access("B"."TAX_AUDIT_RECORD_ID"=:B1)There is no relationship (pk/fk) between both of these tables. PK are being populated by an oracle sequence in both the tables. There are lot of matching ids in both the tables though (1Million).
I dont know why Oracle is using FILTER instead of using join methods. I tried using USE_HASH, USE_NL, USE_SJ, but no luck.
Join column (TAX_AUDIT_RECORD_ID) is NOT NULL in both table definition.
I even tried UNNEST hint in sub-query, but again, i did not get any success.Thanks very much Jonathan for your pointer. (I am regular reader of your blog and wondering how come i missed this one !)
I am getting below error while using LNNVL function:
explain plan for
DELETE FROM A tars where rowid in
(select rowid from A where TR_STATUS IN ('C', 'R')
union all
select rowid from A tars where exists
(SELECT null FROM B taxar WHERE B.TAX_AUDIT_RECORD_ID = A.TAX_AUDIT_RECORD_ID)
and lnnvl(A.TR_STATUS IN ('C', 'R')));
ORA-13207: incorrect use of the [LNNVL] operatorWould i expect same result(row count) with/without this function ?
However, If i remove LNNVL,i get below plan :
Plan hash value: 1196139345
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop | TQ |IN-OUT| PQ Distrib |
| 0 | DELETE STATEMENT | | 513G| 21T| 1434K (77)| 04:46:49 | | | | | |
| 1 | PX COORDINATOR | | | | | | | | | | |
| 2 | PX SEND QC (RANDOM) | :TQ10006 | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,06 | P->S | QC (RAND) |
| 3 | INDEX MAINTENANCE | A | | | | | | Q1,06 | PCWP | | |
| 4 | PX RECEIVE | | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,06 | PCWP | |
| 5 | PX SEND RANGE | :TQ10005 | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,05 | P->P | RANGE |
| 6 | DELETE | A | | | | | | | Q1,05 | PCWP | |
| 7 | PX RECEIVE | | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,05 | PCWP | |
| 8 | PX SEND HASH (BLOCK ADDRESS) | :TQ10004 | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,04 | P->P | HASH (BLOCK|
|* 9 | HASH JOIN BUFFERED | | 513G| 21T| 1434K (77)| 04:46:49 | | | Q1,04 | PCWP | |
| 10 | PX RECEIVE | | 5069K| 159M| 17222 (1)| 00:03:27 | | | Q1,04 | PCWP | |
| 11 | PX SEND HASH | :TQ10002 | 5069K| 159M| 17222 (1)| 00:03:27 | | | Q1,02 | P->P | HASH |
| 12 | PX BLOCK ITERATOR | | 5069K| 159M| 17222 (1)| 00:03:27 | 1 | 32 | Q1,02 | PCWC | |
| 13 | TABLE ACCESS FULL | A | 5069K| 159M| 17222 (1)| 00:03:27 | 1 | 32 | Q1,02 | PCWP | |
| 14 | PX RECEIVE | | 10M| 116M| 322K (3)| 01:04:35 | | | Q1,04 | PCWP | |
| 15 | PX SEND HASH | :TQ10003 | 10M| 116M| 322K (3)| 01:04:35 | | | Q1,03 | P->P | HASH |
| 16 | VIEW | VW_NSO_1 | 10M| 116M| 322K (3)| 01:04:35 | | | Q1,03 | PCWP | |
| 17 | SORT UNIQUE | | 10M| 338M| 322K (95)| 01:04:35 | | | Q1,03 | PCWP | |
| 18 | PX RECEIVE | | | | | | | | Q1,03 | PCWP | |
| 19 | PX SEND HASH | :TQ10001 | | | | | | | Q1,01 | P->P | HASH |
| 20 | BUFFER SORT | | 513G| 21T| | | | | Q1,01 | PCWP | |
| 21 | UNION-ALL | | | | | | | | Q1,01 | PCWP | |
| 22 | PX BLOCK ITERATOR | | 5069K| 67M| 17275 (1)| 00:03:28 | 1 | 32 | Q1,01 | PCWC | |
|* 23 | TABLE ACCESS FULL | A | 5069K| 67M| 17275 (1)| 00:03:28 | 1 | 32 | Q1,01 | PCWP | |
|* 24 | HASH JOIN SEMI | | 5069K| 270M| 305K (4)| 01:01:08 | | | Q1,01 | PCWP | |
| 25 | PX BLOCK ITERATOR | | 5069K| 169M| 17275 (1)| 00:03:28 | 1 | 32 | Q1,01 | PCWC | |
|* 26 | TABLE ACCESS FULL | A | 5069K| 169M| 17275 (1)| 00:03:28 | 1 | 32 | Q1,01 | PCWP | |
| 27 | BUFFER SORT | | | | | | | | Q1,01 | PCWC | |
| 28 | PX RECEIVE | | 276M| 5547M| 287K (4)| 00:57:34 | | | Q1,01 | PCWP | |
| 29 | PX SEND BROADCAST LOCAL| :TQ10000 | 276M| 5547M| 287K (4)| 00:57:34 | | | Q1,00 | P->P | BCST LOCAL |
| 30 | PX BLOCK ITERATOR | | 276M| 5547M| 287K (4)| 00:57:34 | 1 | 8 | Q1,00 | PCWC | |
| 31 | TABLE ACCESS FULL | B | 276M| 5547M| 287K (4)| 00:57:34 | 1 | 8 | Q1,00 | PCWP | |
Predicate Information (identified by operation id):
9 - access(ROWID="ROWID")
23 - filter("A"."TR_STATUS"='C' OR "A"."TR_STATUS"='R')
24 - access("B"."TAX_AUDIT_RECORD_ID"="A"."TAX_AUDIT_RECORD_ID")
26 - filter("A"."TR_STATUS"='C' OR "A"."TR_STATUS"='R')
-
Issue with Multilevel subquerying, correlating out and inner object failing
Hi,
I have a peculiar situation with no idea how to overcome this. Please consider the following example.
I have Table T1 with columns C1 , C2 , C3 and Table T2 with columns D1, D2, and D3.
Here i need to fetch the column C1 and D1 when C2 = D2 or when C3 = D3 and D2 = null. So I wrote a query
Select t1.C1, (select D1 FROM T2 t2 WHERE (t2.D2=t1.C2) OR (t2.D3 = t1.C3 AND t2.D2 is null))
FROM TABLE T1 WHERE t1.C1 = 123456
But here the problem was when I have two records maintained that will satisfy the condition I add a selected around the inner select with the where clause having rownum = 1
ie
Select t1.C1, (select D1 FROM
(select D1 FROM T2 t2 WHERE (t2.D2=t1.C2) OR (t2.D3 = t1.C3 AND t2.D2 is null) order by t2.D2, t2.D3) b
WHERE rownum = 1)
FROM TABLE T1 WHERE t1.C1 = 123456
The reason for taking the rownum outside was that i need to fetch the record where D2 is not null if it is present, therefore forcing me to use an order by clause. If I use rownum in the same inner query it fetches the first row before the order by clause is applied to the result.
But now the problem is that i am getting an error that says t1.C2 and t1.C3 are invalid identifiers. How do i overcome this?Hi,
I am not able to clearly understand your requirement, neither there is any reference data.
Anyways, based on what i could think, I have made the below query, think you can tweek it to suit your requirement.
SQL> CREATE TABLE t1 (c1 NUMBER, c2 NUMBER, c3 NUMBER);
Table created
SQL> CREATE TABLE t2 (d1 NUMBER, d2 NUMBER, D3 NUMBER);
Table created
SQL> INSERT INTO t1 VALUES (1 ,2, 3);
1 row inserted
SQL> INSERT INTO t1 VALUES (4, 5, 6);
1 row inserted
SQL> INSERT INTO t1 VALUES (7, 2, 3);
1 row inserted
SQL> INSERT INTO t2 VALUES (1, null, 3);
1 row inserted
SQL> INSERT INTO t2 VALUES (1, 2, 3);
1 row inserted
SQL> INSERT INTO t2 VALUES (4, 5, 6);
1 row inserted
SQL> INSERT INTO t2 VALUES (4, 5, 6);
1 row inserted
SQL> SELECT c1, c2, c3, d1, d2, d3
2 FROM (SELECT t1.c1,
3 t1.c2,
4 t1.c3,
5 t2.d1,
6 t2.d2,
7 t2.d3,
8 ROW_NUMBER() OVER(PARTITION BY t1.c1, t1.c2, t1.c3, t2.d1, t2.d3 ORDER BY t2.d1, t2.d2, t2.d3) rn
9 FROM t1, t2
10 WHERE (t1.c2 = t2.d2)
11 OR (t1.c3 = t2.d3 AND t2.d2 IS NULL))
12 WHERE rn = 1
13 /
C1 C2 C3 D1 D2 D3
1 2 3 1 2 3
4 5 6 4 5 6
7 2 3 1 2 3
SQL> Regards
Ameya -
Issue with Duplicate Results and Summary Fields
My report is based on an Access Database. For the purposes of this current issue, there is the Master Table called u201CCnu201D and then a related u201CTable Au201D which includes multiple records related to the Master and also a related u201CTable B,u201D also with multiple records related to the Master.
For my report, I want to output results from Table B based on criteria in Table A. This naturally produces duplicate output on the report. As a result, the Summary Fields that I want to include are incorrect.
I have tried multiple combinations of the Select Distinct function, suppression based on u201Cprevious fieldu201D being equal, summary fields, running totals and if-then statements and still cannot find a solution that works in all of the cases involved.
Below are descriptions of three different scenarios that are occurring:
EXAMPLE #1: Entry 1 has 2 records in Table A and 2 Records in Table B so "Select Distinct" including the Table B ID # and then a Summary Field for the Total produces the correct results, while a Running Total is Incorrect.
EXAMPLE #2: Entry 2 has 2 records in Table A and 1 Record in Table B so a suppression formula of the field based on the "Previous =" Table B ID # and the Running Total produce the correct results, while Summary Field is incorrect.
EXAMPLE #3: Entry 3 has 6 records in Table A and 6 Records in Table B. Neither Summary or
Running Totals produce correct results.
I would greatly appreciate any advice in terms of creative formulas, etc. that would help produce correct results here.
Iu2019ll be pulling my hair out soon! Thanks so much-Hi Berry
Try to create a command with a subquery. The subquery will be returning the the duplicate records and the main query that uses this subquery will find distinct records out of the resultset returned by the subquery.
Let me know if this helps.
Regards
Nikhil -
SQL query with lots of conditions issue..
Working on A large query that hits a large DB of parts.
The table I am given these parts are broken up into 4 fields.
Section,Groupid,Subgroupid,Component
When I hit this table, i am given a list of all the possible combo's of the 4 fields that can be used for that lookup at that time.
The problem is its SLOW when this list is pretty big.. a lot of times, over 200 rows of combos... so end up with something like below,
but stripped down for explaining...
So a generic version the query..
Select * from PartTable where
( (section='blah1') and (groupid='blah2') and (subgroupid='blah3') and (component='blah4') ) or
( (section='blah5') and (groupid='blah6') and (subgroupid='blah7') and (component='blah8') ) or
( (section='blah9') and (groupid='blah10') and (subgroupid='blah11') and (component='blah12') ) or
( (section='blah250') and (groupid='blah251') and (subgroupid='blah252') and (component='blah253') )I have changed it to a deal where I have a subquery and do a case statement to query a subquery, but the problem I run into that
is, is that 10g only allows so many. I can get around this by when i generate the query, to just make multiple case statements and then
modify my where statement.. but seems sloppy.. but "Works" .. using the OR statement deal, it can take near 30 seconds... with the
sloppy looking multiple case statement field deal, it takes 1.6 seconds..870023 wrote:
Try creating Index on these columns. Will help in CPU cost.That is one of the most useless pieces of advice I have ever seen.
CPU cost does not necessarily reflect performance. Creating too many indexes can also slow down performance. The first way of tackling a performance issue is to find out what the cause is, before trying to figure out the best way to fix it.
{message:id=9360003} -
How can I remove distinct from subquery?
Hello, I'll expose my problem, I don't know if may be is a bug.
Suppose We have
Table A:
field A1 primary key
field A2
field A3
Table B
field B1 primary key
field B2 foreig key to A(A1)
field B3
I use reverse tool to build objects from DB schema.
Everything runs ok but when I want to recover A objects
with sum(B3) from B,it doesn't runs fine.
To achieve this I've made a class C with fields of class A and a double
for sum. The code I've use is:
KodoQuery query = (KodoQuery)getPersistenceManager()
.newQuery(A.class, "this == b.b2");
query.declareVariables("B b");
query.declareImports("x.x.B");
query.setResultClass(C.class);
query.setResult("this as a, sum(b.b3) as s");
query.setGrouping("a");
Collection c = query.execute();
I use PostGreSQL 7.4, and the sql that Kodo generates is like this:
SELECT s.A1, SUM(s.C) AS c
FROM ( SELECT DISTINCT a.A1 AS A1, s.B3 AS C
FROM PUBLIC.A a INNER JOIN PUBLIC.B b ON (a.A1 = b.B2) ) s
GROUP BY s.A1
But the problem is 'DISTINCT' keyword. If I have records on B
with same B3 value then:
B1=1,B2=1,B3=25
B1=2,B2=1,B3=25
The query returns SUM(B3)=25 which is not valid!!!, it must be 50.
It fails with repeated B3 values because distinct keyword.
I bypass this adding a third field to class C that I will not use, and
introduce it into query:
KodoQuery query = (KodoQuery)getPersistenceManager()
.newQuery(A.class, "this == b.b2");
query.declareVariables("B b");
query.declareImports("x.x.B");
query.setResultClass(C.class);
query.setResult("this as a, sum(b.b3) as s, sum(b.b1) as t");
query.setGrouping("a");
Collection c = query.execute();
With this, I force to put primary key into subquery, and disables
DISTINCT, but I never will use this field :(. SQL generated by KODO:
SELECT s.A1, SUM(s.C) AS c, SUM(s.T) as t
FROM ( SELECT DISTINCT a.A1 AS A1, s.B3 AS C, s.B1 as T
FROM PUBLIC.A a INNER JOIN PUBLIC.B b ON (a.A1 = b.B2) ) s
GROUP BY s.A1
Questions:
1.- What may I doing wrong?
2.- How can I disable Distinct from subquerys?
And, no, I don't want to select by class B and then search A objects.
I want a C object with A object plus SUM of values from B.
I am achieving this with this patch.
I know that when there aren't B objects I don't receive results.
Is there any way to build an OUTER JOIN with JDOQL ?
In order to bypass this, I execute the query another time but reseting to
0, but I will prefer to be able to build an OUTER JOIN ;)
PD: Little class descriptions:
class A{ int a1, int a2, int a3} (autogenerated by kodo)
class B{ int b1, int b2, double b3} (autogenerated by kodo)
class C{ A a, double c, int t} (generated by me)
Sorry for my english :(
thanks.I'll address your outer join question first, since it's the easiest. Kodo will
create outer joins automatically as needed to satisfy your JDOQL. In this case,
your JDOQL does not warrant an outer join. Your filter criteria on the query is
"this == b.b2". That means the query cannot and should not return any values
when there are no A's that match that join. Why not try this equivalent but
simpler query?
Query q = pm.newQuery (B.class);
q.setResult ("b2 as a, sum(b3) as s");
q.setGrouping ("b2");
q.setResultClass (C.class);
That will return results grouped by the A objects from the b2 field, and the sum
of the b3 field for all B's in each group. It should use an outer join.
About DISTINCT:
The pattern of a distinct subselect is caused by two conditions:
1. Your result clause is non-distinct. That is, you did:
q.setResult("this as a, sum(b3) as s")
rather than:
q.setResult("distinct this as a, sum(b3) as s")
This means that you want to allow duplicates in the projected values you get back.
2. You use an unbound variable ("b") in a way that could lead to duplicates
caused by relational joins. JDO always eliminates duplicates caused by database
joins.
So in order to eliminate the possible duplicates caused by #2, Kodo issues the
query as a DISTINCT subselect. Then in order to allow duplicates of the
projected results (#1), Kodo uses a non-distinct outer select.
The simplest way to eliminate the DISTINCT subselect is to use the alternate
query on B.class I mentioned above. That will result in no DISTINCTs at all.
Another way is to use the "distinct" keyword in your setResult() call, as I
showed in #1. That will result in a DISTINCT select without any subselect.
Without reverting to a SQL query (which you can still execute through JDO APIs,
as described in the documentation), I believe those are the options available. -
11g-[nQSError: 42029] Subquery contains too many values for the IN predicat
Hi,
I am having 2 reports one is for subquery which returns inputs to Main report. Actually the report was working fine in 10g. But in 11g we are gettting following error:
View Display Error
Odbc driver returned an error (SQLExecDirectW).
Error Details
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 43119] Query Failed: [nQSError: 42029] Subquery contains too many values for the IN predicate.Please have your System Administrator look at the log for more details on this error. (HY000)
Please have your System Administrator look at the log for more details on this error.
Getting same error after modofying the parameter value MAX_EXPANDED_SUBQUERY_PREDICATES to 12000
Please suggest what could be the other reason it may fail or any other settings we need to check.
Regards,
ckengckeng,
Normally the IN clause has restriction of 10000 values in general sql/plsql we will go with inline queries i think model your rpd to generate inner queries
select * from emp where dept_id in (Select distinct dept_id from dept);
or have a condition/filter on sub report and make one more inner report with sub-filter but definitely it will cause performance issues.
thanks,
Saichand.v
Maybe you are looking for
-
AP Credit Note picking wrong tax code
Dear All, When I copy a AP credit memo from an AP Invoice, it is not picking the tax code of the invoice. The tax code column is not active as well. i suspect it is picking the suppliers tax group instead of the invoice from which it is copied. Pleas
-
How to unlock MacBook Air that was purchased used
I just purchased a MacBook Air from RAC. I opened it and the previous user, or a employee at RAC hadn't closed things down. As I was closing things getting ready to try and reset it. The computer returned to the log in page. Now the computer is locke
-
Adusting video input signal while capturing???
Hello I'm running Final Cut HD and am having trouble adjusting my video input signal. Under "Clip Settings" in the Capture Tool there appear to be controls, but they are disabled and my scopes do not appear to be reading either. Any thoughts on how t
-
Time machine issue after Yosemite install
After performing a clean install of Yosemite and migration from my TimeMachine backup I experienced the following: I opened iTunes and selected some music to play, then got a dialog box saying the files could not be found. Spotlight couldn't find th
-
Help, How can I split an activity in SAP-PS
Hello, Trying to split an activity in a project, cannot find any information on how to do it. (fonctionality is available in MS-Project, new user to SAP-PS) Situation: Activity starts and after 4days, it is put on hold for 5days and then restarts. H