Messy One to Many Joins and Grouping
I manage websites for a large state agency in Texas. I have a
need to redo
queries that list the Local intake numbers for Long term
support services
(LTSS), Area Agencies on Aging (AAA), and Mental Retardation
Authorities
(MRA) by county for each of the state's 254 counties -- in
the past there
was only one intake number per county for each AAA and MRA,
with there being
the possibility for multiple LTSS intake numbers. Now there
are counties
that have multiple numbers for MRA intake.
Basic Structure of Database Tables:
CountyCenter Table
County (text)
CountyNumber (integer)
AAA_ID (integer)
MRA_ID (integer)
LTSS Table
County (text)
CountyNumber (integer)
City (text) -- optional used when there are multiple offices
for a county
IntakeNumber (text)
Region (text)
AAA Table
AAA_ID (integer)
AAAName (text)
AAAPhone (text)
MRA Table
MRA_ID (integer)
MRAName (text)
MRAPhone
MRAOffices
MRA_ID (integer)
IntakePhone (text)
City (Text)
CountyNumber (integer)
My goal is for each county to list in a combined table:
Column 1 = County Name
Column 2 = LTSS Office (Number(s))
Column 3 = MRA Intake Number
Column 4 = AAA Intake Number(s)/City if not main
Do I need a separate table for county that simply has the
CountyNumber and
CountyName to use as a control table?
I'd like to do this as efficiently as possible -- thankfully
the query won't
be accessed by the general public and will be run only when
updated
information is received. Any suggestions as to order of the
joins and
groupings in CFOUTPUT? (what I have now creates a lot of
duplication)
Thanks in advance for your help,
Michael Brown
Webmaster, Texas Department of Aging and Disability Services
Phil,
Thanks for taking a look. You're definitely right. The data
structures are a mess. What was originally intended to be on
three
separate pages has been requested to be "available at a
glance."
With both the LTSS Offices and MRAs having the possiblity of
multiple offices for a given county what would be the best
way to
normalize the data? The tables for MRA, AAA, and LTSS have
CountyNumber (county exists only in those tables to provide
context for those who update the information manually (not my
choice/decision)).
So to break it down 254 Counties, each can have one or
multiple
LTSS numbers (and the number's city), only one AAA number,
and one
MRA with the possiblity for multiple intake numbers (and note
containing location information).
Hopefully, there is a graceful way of getting the output the
way
it has been requested. I'm open to suggestions.
Thanks again,
Michael
"paross1" <[email protected]> wrote in
news:[email protected]:
> After taking a quick glance, it looks like you already
have
> normalization issues with your data model, since LTSS
Table and
> CountyCenter Table both contain County (text), and
MRAOffices
and LTSS
> Table both have City (text), etc. It is hard to tell
which
fields are
> primary keys and which are foreign keys to which tables.
Some of
these
> that may have a one-to-many relationship that now
changes to a
> many-to-many will require a link table (associative
entity) and
the
> foreign keys migrated to them.
>
> You need to resist creating actual "combined tables",
spreadsheet
> style, and
> instead normalize your database, so that you can create
your
"combined
> table" virtually using SQL. It is hard to offer
specifics, since
I
> would need more information to do so, but the bottom
line is
that you
> do have some obvious data model issues that need to be
resolved
before
> you can get much further. Otherwise, you are going to
have to
write
> some very kludgey SQL to solve your problem with your
current
model.
>
> Phil
>
>
Similar Messages
-
How just return one row of a one to many join..
So I have a one to many join where the SMOPERATOR table has data I need however it has a couple of rows that match the JOIN condition in there. I just need to return one row. I think this can be accomplished with a subquery in the join however have not been able to come up with the right syntax to do so.
So:
SELECT "NUMBER" as danumber,
NAME,
SMINCREQ.ASSIGNMENT,
SMOPERATOR.PRIMARY_ASSIGNMENT_GROUP,
SMOPERATOR.WDMANAGERNAME,
SMINCREQ.owner_manager_name,
SMINCREQ.subcategory, TO_DATE('01-'||TO_CHAR(open_time,'MM-YYYY'),'DD-MM-YYYY')MONTHSORT,
(CASE WHEN bc_request='f' THEN 'IAIO'
WHEN (bc_request='t' and substr(assignment,1,3)<>'MTS') THEN 'RARO'
WHEN (bc_request='t' and substr(assignment,1,3)='MTS') THEN 'M'
ELSE 'U' end) as type
from SMINCREQ
left outer join SMOPERATOR on SMINCREQ.assignment=SMOPERATOR.primary_assignment_group
WHERE SMINCREQ.owner_manager_name=:P170_SELECTION and SMOPERATOR.wdmanagername=:P170_SELECTION
AND open_time BETWEEN to_date(:P170_SDATEB,'DD-MON-YYYY') AND to_date(:P170_EDATEB,'DD-MON-YYYY')
AND
(bc_request='f' and subcategory='ACTIVATION' and related_record<>'t')
OR
(bc_request='f' and subcategory<>'ACTIVATION')
OR
(bc_request='t' and substr(assignment,1,3)<>'MTS')
order by OPEN_TIMeHi,
This sounds like a Top-N Query , where you pick N items (N=1 in this case) off the top of an orderded list. I think you want a separate ordered list for each assignment; the analytic ROW_NUMBER function does that easily.
Since you didn't post CREATE TABLE and INSERT statements for your sample data, I'll use tables from the scott schema to show how this is done.
Say you have a query like this:
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
ORDER BY dname
;which produces this output:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7934 MILLER CLERK 1300
ACCOUNTING 7839 KING PRESIDENT 5000
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
RESEARCH 7902 FORD ANALYST 3000
RESEARCH 7566 JONES MANAGER 2975
RESEARCH 7369 SMITH CLERK 800
RESEARCH 7788 SCOTT ANALYST 3000
SALES 7521 WARD SALESMAN 1250
SALES 7844 TURNER SALESMAN 1500
SALES 7499 ALLEN SALESMAN 1600
SALES 7900 JAMES CLERK 950
SALES 7698 BLAKE MANAGER 2850
SALES 7654 MARTIN SALESMAN 1250Now say you want to change the query so that it only returns one row per department, like this:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
SALES 7499 ALLEN SALESMAN 1600where the empno, ename, job and sal columns on each row of output are all taken from the same row of scott.emp, though it doesn't really matter which row that is.
One way to do it is to use the analytic ROW_NUMBER function to assign a sequence of unique numbers (1, 2, 3, ...) to all the rows in each department. Since each sequence startw with 1, and the numbers are unique within a department, there will be exactly one row per departement that was assigned the numebr 1, and we''ll display that row.
Here's how to code that:
WITH got_r_num AS
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
, ROW_NUMBER () OVER ( PARTITION BY d.dname
ORDER BY e.ename
) AS r_num
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
SELECT dname
, empno, ename, job, sal
FROM got_r_num
WHERE r_num = 1
ORDER BY dname
;Notice that he sub-query got_r_num is almost the same as the original query; only it has one additional column, r_num, in the SELECT clause, and the sub-qeury does not have an ORDER BY clause. (Sub-queries almost never have an ORDER BY clause.)
The ROW_NUMBER function must have an ORDER BY clause. In this example, I used "ORDER BY ename", meaning that, within each department, the row with the first ename (in sort order) will get r_num=1. You can use any column, or expression, or expressions in the ORDER BY clause. You muight as well use something consistent and predictable, like ename, but if you really wanted arbitrary numbering you could use a constant in the analytic ORDER BY clause, e.g. "ORDER BY NULL". -
hi anyone to there know how to fix my problem. my mom tried my password one two many times and now my phone is disabled and i cant use it unless its a emergency.
iOS: Forgot passcode or device disabled
I hope you back up on a regular basis. -
How to resolve many-to-many join by 2 one-to-many joins
Hi,
I was asked many times how to resolve many to many relationship between two tables. I read to use 2 one -to- many relationships to resolve this. Can some expalin me when many to many relationship occurs between two tables and how to reslove them with practicle examples. Is there any article on this?
Regards,
Nanda KishoreHi,
Please check below link.
http://www.forumtopics.com/busobj/viewtopic.php?p=859029&sid=20d79e3df07b0d8b41aadfbd902bb6b2
http://blog.oaktonsoftware.com/2011/04/bridge-tables-and-many-to-many.html
Thanks,
Amit -
Need help in optimizing the query with joins and group by clause
I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
CREATE TABLE FILE_STATUS
(FILE_ID VARCHAR2(14),
FILE_NAME VARCHAR2(20),
CARR_CD VARCHAR2(5),
TOT_REC NUMBER,
TOT_SUCC NUMBER);
CREATE TABLE COMM
(SRC_FILE_ID VARCHAR2(14),
REC_ID NUMBER,
STATUS CHAR(1));
INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
INSERT INTO COMM VALUES ('12345678', 1, 'T');
INSERT INTO COMM VALUES ('12345678', 3, 'T');
INSERT INTO COMM VALUES ('12345678', 4, 'P');
INSERT INTO COMM VALUES ('12345678', 5, 'P');
COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
SELECT
FS.CARR_CD
,FS.FILE_NAME
,FS.FILE_ID
,FS.TOT_REC
,FS.TOT_SUCC
,NVL(C.TOT_TRANS, 0) TOT_TRANS
FROM FILE_STATUS FS
LEFT JOIN
SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
FROM COMM
WHERE STATUS = 'T'
GROUP BY SRC_FILE_ID
) C ON C.SRC_FILE_ID = FS.FILE_ID
WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
from (select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM')
where rn = 1;
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS
LIBM CM_LIBM.TXT 12345678 5 4 2
LIBM CM_LIBM.TXT 12345677 10 0 0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM';
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS RN
LIBM CM_LIBM.TXT 12345678 5 4 2 1
LIBM CM_LIBM.TXT 12345678 5 4 2 2
LIBM CM_LIBM.TXT 12345678 5 4 2 3
LIBM CM_LIBM.TXT 12345678 5 4 2 4
LIBM CM_LIBM.TXT 12345677 10 0 0 1 -
One-to-many mapping and update the many part
Hello !
Here's my problem,
I've got an object A having a vector of object B.
The mapping in toplink is one-to-many with the back-references set in B.
Insertion : no problem.
Now i would like to change the Vector of B (inserting new B, updating existing B) in a function with the Vector vC (modified vector of B).
What is the best way to do this ?
I tried many thing but either I have toplink 6004 error, or doing it by removing all elements of the Vector (deleting all B in database), and then setting A with C (recreating all object in the modified Vector).
Another way to explain my case:
how to do this in UnitOfWork ?
function modifyAVectorOfB(A, vectorOfC)
AClone = uow.registerObject(A);
Aclone.setVectorOfB(vectorOfC);
uow.commit;
(and in database all existing object in C are updated, new object in C are created, removed object in C are deleted)Have found a solution, read all object in the modified Vector, read the modified object in the Unit Of Work with readObject(B) (So i get the database or cache version) and then comparing it with the modified to change what is needed to be change.
-
EA1 - SQL Formatter issues (JOINs and GROUPs and ORDER BY oh my ;)
Great job with improving the SQL Formatter, but it still has some bugs that need to be worked out.
The key words JOIN and it's modifiers INNER, LEFT, RIGHT and FULL OUTER are not recognized as master key words. As such they end up flush against the left margin Also when GROUP BY and/or ORDER BY key words are present in an outer most select statement the other key words are not indented far enough to be right aligned with the end of the word BY and are indented too far to be right aligned with the word GROUP or ORDER. In sub queries, GROUP and ORDER BY are correctly right aligned with their respective SELECT statements.We're picking up and collating the Formatter issues. I'll add these.
Specific bug for these #7013462
Sue -
Rewrite the query with out joins and group by
Hi,
This was an interview question.
Table Names: bookshelf_checkout
bookshelf
And the join condition between these two tables is title
We need to rewrite below query without using join condition and group by clause ?
SELECT b.title,max(bc.returned_date - bc.checkout_date) "Most Days Out"
FROM bookshelf_checkout bc,bookshelf b
WHERE bc.title(+)=b.title
GROUP BY b.title;When I was in college, I read that most of the SELECT statements can be replaced by basic SQL operations (SET OPERATORS). Now I am trying to rewrite the query with SET operators but not able to get the exact result.
Kindly help me on this.
Thanks,
SuriSomething like this?
1 WITH books AS (
2 SELECT 'title 1' title FROM dual UNION ALL
3 SELECT 'title 2' FROM dual UNION ALL
4 SELECT 'title 3' FROM dual ),
5 bookshelf AS (
6 SELECT 'title 1' title, DATE '2012-05-01' checkout_date, DATE '2012-05-15' returned_date FROM dual UNION ALL
7 SELECT 'title 1' title, DATE '2012-05-16' checkout_date, DATE '2012-05-20' returned_date FROM dual UNION ALL
8 SELECT 'title 2' title, DATE '2012-04-01' checkout_date, DATE '2012-05-15' returned_date FROM dual )
9 SELECT bs.title, MAX(bs.returned_date - bs.checkout_date) OVER (PARTITION BY title) FROM bookshelf bs
10 UNION
11 (SELECT b.title, NULL FROM books b
12 MINUS
13* SELECT bs.title, NULL FROM bookshelf bs)
SQL> /
TITLE MAX(BS.RETURNED_DATE-BS.CHECKOUT_DATE)OVER(PARTITIONBYTITLE)
title 1 14
title 2 44
title 3Lukasz -
One to many mappings and combination generation
Please help folks,
I want to perform one to many mapping i.e a single row of data will be taken from a single table Table 'A' into Hashtable A and it has to be matched with 'n' number of rows from another table Table 'B' taken into Hashtable B. The no. of rows selected from B can be 1/2.... upto n. For performing this mapping iam using a Combination Generator Code which will Key nos. to be selected for checking whether they can be mapped and then further processing is done on these key nos. returned by the combination generator. The code for combination generator is given below.
The issue is say if there are about 50 rows in table B then no of combinations possible are 2 ^ 50, which is just too much for the PC to handle i.e the code takes about 4-5 days of processing time. 256 MB RAM, P4. The mapping has to be done in 30 minutes!!!! Ne ideas folks????
// Systematically generate combinations.
import java.math.BigInteger;
public class CombinationGenerator {
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
// Constructor
public static void main(String[] args)
String[] elements = {"a", "b", "c", "d", "e", "f", "g"};
int[] indices;
CombinationGenerator x = new CombinationGenerator (elements.length, 3);
StringBuffer combination;
while (x.hasMore ()) {
combination = new StringBuffer ();
indices = x.getNext ();
for (int i = 0; i < indices.length; i++) {
combination.append (elements[indices[i]]);
System.out.println (combination.toString ());
public CombinationGenerator (int n, int r) {
if (r > n) {
throw new IllegalArgumentException ();
if (n < 1) {
throw new IllegalArgumentException ();
this.n = n;
this.r = r;
a = new int[r];
BigInteger nFact = getFactorial (n);
BigInteger rFact = getFactorial (r);
BigInteger nminusrFact = getFactorial (n - r);
total = nFact.divide (rFact.multiply (nminusrFact));
reset ();
// Reset
public void reset () {
for (int i = 0; i < a.length; i++) {
a[i] = i;
numLeft = new BigInteger (total.toString ());
// Return number of combinations not yet generated
public BigInteger getNumLeft () {
return numLeft;
// Are there more combinations?
public boolean hasMore () {
return numLeft.compareTo (BigInteger.ZERO) == 1;
// Return total number of combinations
public BigInteger getTotal () {
return total;
// Compute factorial
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fact = fact.multiply (new BigInteger (Integer.toString (i)));
return fact;
// Generate next combination (algorithm from Rosen p. 286)
public int[] getNext () {
if (numLeft.equals (total)) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
int i = r - 1;
while (a[i] == n - r + i) {
i--;
System.out.println("inside while");
a[i] = a[i] + 1;
for (int j = i + 1; j < r; j++) {
a[j] = a[i] + j - i;
numLeft = numLeft.subtract (BigInteger.ONE);
return a;Next time you post, see the formatting guidelines [url http://forum.java.sun.com/features.jsp#Formatting]here. //--------------------------------------
// Systematically generate combinations.
import java.math.BigInteger;
public class CombinationGenerator {
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
// Constructor
public static void main(String[] args)
String[] elements = {"a", "b", "c", "d", "e", "f", "g"};
int[] indices;
CombinationGenerator x = new CombinationGenerator (elements.length, 3);
StringBuffer combination;
while (x.hasMore ()) {
combination = new StringBuffer ();
indices = x.getNext ();
for (int i = 0; i < indices.length; i++) {
combination.append (elements[indices]);
System.out.println (combination.toString ());
public CombinationGenerator (int n, int r) {
if (r > n) {
throw new IllegalArgumentException ();
if (n < 1) {
throw new IllegalArgumentException ();
this.n = n;
this.r = r;
a = new int[r];
BigInteger nFact = getFactorial (n);
BigInteger rFact = getFactorial (r);
BigInteger nminusrFact = getFactorial (n - r);
total = nFact.divide (rFact.multiply (nminusrFact));
reset ();
// Reset
public void reset () {
for (int i = 0; i < a.length; i++) {
a = i;
numLeft = new BigInteger (total.toString ());
// Return number of combinations not yet generated
public BigInteger getNumLeft () {
return numLeft;
// Are there more combinations?
public boolean hasMore () {
return numLeft.compareTo (BigInteger.ZERO) == 1;
// Return total number of combinations
public BigInteger getTotal () {
return total;
// Compute factorial
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fact = fact.multiply (new BigInteger (Integer.toString (i)));
return fact;
// Generate next combination (algorithm from Rosen p. 286)
public int[] getNext () {
if (numLeft.equals (total)) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
int i = r - 1;
while (a == n - r + i) {
i--;
System.out.println("inside while");
a = a + 1;
for (int j = i + 1; j < r; j++) {
a[j] = a + j - i;
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
} -
JPA one to many relationship and serialization
Hi,
I modeled a one to may relationship like this:
Parent Class WFData:
@OneToMany(mappedBy = "wfData", targetEntity = Positionen.class)
private Set<Positionen> positionen;
Child Class Positionen
@ManyToOne
@JoinColumn(name = "WF_REF_ID", referencedColumnName = "ID")
private WFData wfData;
Now I want to create an EJB session bean with a method which returns an object of type WFData (parent) published as web service . When I try to deploy the web service I get the following error message: Unable to generate serialization framework for web service
Does anyone know how to serialize a one-to-many relationship so I can use these objects in a web service?
Best regards,
KevinI found the solution to get serialization correctly working and enable the service to be used in Visual Composer.
You need to add the tag @XmlTransient to the getter method of the attribute in the child class that references the parent.
@XmlTransient
public WFData getWfData() {
return wfData; -
Why do I have so many Users and Groups (RDN) on my computer?
I have had trouble viewing certain documents. I've been told I don't have permission. When I checked the Users, I find a list of Users and Groups that I'm unaware of. My computer should only be used by myself and my daughter. How do I know which Users to
keep, and which to get rid of? How do I delete unwanted users? I do belong to a group. My computer was given to me by my former employer. Does he still have access to my files?
These are the additional users and Groups listed on my computer...
Account Manager 101
Administrator
Administrators
ANONYMOUS LOGON
Authenticated Users
Backup Operators
Batch
CONSOLE LOGON
CREATOR GROUP
CREATOR OWNER
Cryptograph Operators
Dialup
Distributed COM Users
Event Log Readers
Everyone
Guest
Guests
Homegroupusers$
HomeUsers
IIS_IUSRS
INTERACTIVE
IUSR
Local Account
Local Account and Member of Administrators Group
LOCAL SERVICE
Mackenzie Victor
NETWORK
Network Configuration Operators
NETWORK SERVICE
OWNER RIGHTS
Performance Log Users
Performance Monitor Users
Power Users
Remote Desktop Users
REMOTE INTERACTIVE LOGON
Replicator
SERVICE
SYSTEM
TERMINAL SERVICE USER
This Organization Certificate
Users
Some of which have access to my folders, others do not. Is this something that should concern me?I have had trouble viewing certain documents. I've been told I don't have permission. When I checked the Users, I find a list of Users and Groups that I'm unaware of. My computer should only be used by myself and my daughter. How do I know which Users to
keep, and which to get rid of? How do I delete unwanted users? I do belong to a group. My computer was given to me by my former employer. Does he still have access to my files?
These are the additional users and Groups listed on my computer...
Account Manager 101
Administrator
Administrators
ANONYMOUS LOGON
Authenticated Users
Backup Operators
Batch
CONSOLE LOGON
CREATOR GROUP
CREATOR OWNER
Cryptograph Operators
Dialup
Distributed COM Users
Event Log Readers
Everyone
Guest
Guests
Homegroupusers$
HomeUsers
IIS_IUSRS
INTERACTIVE
IUSR
Local Account
Local Account and Member of Administrators Group
LOCAL SERVICE
Mackenzie Victor
NETWORK
Network Configuration Operators
NETWORK SERVICE
OWNER RIGHTS
Performance Log Users
Performance Monitor Users
Power Users
Remote Desktop Users
REMOTE INTERACTIVE LOGON
Replicator
SERVICE
SYSTEM
TERMINAL SERVICE USER
This Organization Certificate
Users
Some of which have access to my folders, others do not. Is this something that should concern me?
I have something the same only mine is a new pc who can I trust -
Hello All,
I'm trying to update several colums of a table from a inner join query.
First a retrieve the rows afected and the values that I need for the update (I call this subquery ED_Query).
It's important to note that this subquery has a group by and and having clause.
My first attemp (using the query that work in SQL Server query) fails:
SQL> update ED_Update
2 set ED_Update.dtHoraInicioReal = ED_Query.dtHoraInicioReal,
3 ED_Update.dtHoraFinReal = ED_Query.dtHoraFinReal,
4 ED_Update.fPorcentajeRealizado = ED_Query.fPorcentajeRealizado
5 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED_Update
6 inner join (
7 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
8 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
9 MAX(HPP.iOrden) as iOrdenUltimaParada,
10 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
11 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
12 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado
13 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
14 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
15 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
16 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
17 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
18 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal
19 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
20 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
21 ) ED_Query
22 on ED_Update.iIdExpedicionDiaria = ED_Query.iIdExpedicionDiaria;
ERROR at line 5:
ORA-00933: SQL command not properly ended
The subquery (ED_Query) work fine in Oracle, so I suspect that the problems are when I mix it with the update clause.
SQL> select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
2 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
3 MAX(HPP.iOrden) as iOrdenUltimaParada,
4 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
5 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
6 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
7 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
8 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
9 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
10 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
11 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
12 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
13 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal, ED.fPorcentajeRealizado
14 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
15 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal);
IIDEXPEDICION IIDEXPEDICIONDIARIA INUMPARADAS IORDENULTIMAPARADA DTHORAINI
DTHORAFIN FPORCENTAJEREALIZADO ED_DTHORA ED_DTHORA ED_FPORCENTAJEREALIZADO
-131076 5662 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5663 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5664 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
After reading this forum, I change the query and try the next one:
SQL> UPDATE
2 (
3 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
4 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
5 MAX(HPP.iOrden) as iOrdenUltimaParada,
6 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
7 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
8 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
9 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
10 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
11 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
12 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
13 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
14 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
15 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal,ED.dtHoraFinReal, ED.fPorcentajeRealizado
16 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
17 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
18 )
19 SET ED_dtHoraInicioReal = dtHoraInicioReal,
20 ED_dtHoraFinReal = dtHoraFinReal,
21 ED_fPorcentajeRealizado = fPorcentajeRealizado;
ERROR at line 2:
ORA-01732: data manipulation operation not legal on this view
Some help?
Thanl in advance.
Edited by: 984483 on 28-ene-2013 1:48Thanks for your answer. I tried to rewrite my question.
SQL> select * from v$version;
BANNER
Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
PL/SQL Release 9.2.0.3.0 - Production
CORE 9.2.0.3.0 Production
TNS for 32-bit Windows: Version 9.2.0.3.0 - Production
NLSRTL Version 9.2.0.3.0 - Production
I have 2 tables. I like to update one of them (ED_Update) with the data from the another one (ED_Query).
This example is equivalent:
create table ED_Query (id number,
date01 date,
number01 number)
insert into ED_Query values (1, to_date('01/01/2013','DD/MM/YYYY'), 10);
insert into ED_Query values (2, to_date('01/01/2013','DD/MM/YYYY'), 20);
insert into ED_Query values (3, to_date('01/01/2013','DD/MM/YYYY'), 30);
insert into ED_Query values (4, to_date('02/01/2013','DD/MM/YYYY'), 40);
insert into ED_Query values (5, to_date('03/01/2013','DD/MM/YYYY'), 50);
create table ED_Update (date01 date,
numberMax number,
numberSum number)
insert into ED_Update values (to_date('01/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('02/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('03/01/2013','DD/MM/YYYY'), 0, 0);
The next update query fails with ORA-00933: SQL command not properly ended.
update ED_Update
set ED_Update.date01 = ED_Query.date01,
ED_Update.numberMax = ED_Query.numberMax,
ED_Update.numberSum = ED_Query.numberSum
inner join
select date01, max (number01) as numberMax, sum(number01) as numberSum
from ED_Query
where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
I think the problem is in the update clause because the next query work:
select * from
ED_Update
inner join
select date01, max (number01) as numberMax, sum(number01) as numberSum
from ED_Query
where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
Thank in advance. -
Hi Friends,
My code is;
SELECT T1~NUMBER SUM( T2~QUANT )
INTO (ZTABLE1-NUMBER, ZTABLE2-QUANT)
FROM ZTABLE1 AS T1
INNER JOIN ZTABLE2 AS T2
ON T1~NUMBER = T2~NUMBER
GROUP BY T2~VBELN.
ENDSELECT.
I am getting an error as;
The field T1~NUMBER from SELECT is missing in the GROUP BY clause. addition INTO wa or INTO(g1,...,gn) is required. fields of type "" or "T2-VBELN".
I couldn't understand anything from the error message. Can you help what the error message says and how can I do my desire on above query.
Thanks.Usually GROUP BY Is used to get only aggregated fields.
It is not meant for regular selection of fields.
Instead do a regular selection of all the fields without group by and do your aggregation in program logic as per your requirement.
In that way your performance will be better.
Regards
Sudhir Atluru -
Help with exercise on joins and group by
Could someone help me with an exercise I'm working on? This isn't "homework", per se, as it's not an assignment, I'm just doing my own personal research.
I have the usual tables "DEPARTMENT" and "EMPLOYEE", with the following columns:
Department:
* NAME
* ID
Employee:
* SSN
* NAME
* DEPT_ID
* SALARY
I'm able to build a query that summarizes the departments with total employee salary > 30000, like this:
select dept_id, sum(salary) from employee group by dept_id having sum(salary) > 30000;
What I'd like to extend this to is a summary of departments with total employee salary > 30000 OR no employees at all (or total salary = 0, conceptually).
I imagine this will include a left outer join, but I can't get this to work.http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/aggreg.htm#sthref1670
http://www.oracle.com/technology/products/oracle9i/daily/oct10.html
http://www.dba-oracle.com/t_sql99_with_clause.htm
http://www.psoug.org/reference/with.html
WITH clause is used for reusability of sub queries within a query. And in this case it is useful to build the query without having to create a table with data and show the results.
SQL> select 1 dept_id, 'ABC' dept_name from dual;
DEPT_ID DEP
1 ABCHere I am selecting some static values from dual table where I say I want 1 as dept_id and its name as ABC.
SQL> select 1 dept_id, 'ABC' dept_name from dual union all
2 select 2 dept_id, 'XYZ' dept_name from dual union all
3 select 3 dept_id, 'MNO' dept_name from dual;
DEPT_ID DEP
1 ABC
2 XYZ
3 MNOIn the above query I am selecting 3 static department ids and names in three separate queries and combining them using union all. Thus I am getting them as three rows.
SQL> with dept as(
2 select 1 dept_id, 'ABC' dept_name from dual union all
3 select 2 dept_id, 'XYZ' dept_name from dual union all
4 select 3 dept_id, 'MNO' dept_name from dual )
5 --
6 select * from dept;
DEPT_ID DEP
1 ABC
2 XYZ
3 MNOHere, In the above query, I just named the previous query as "dept" and I am just selecting all from "dept". You can say it something like a virtual table which has data based on a query, that can be reused in other/main query. The limitations, uses and elaborate descriptions are available in the links I provided. -
my daughter has a brand new ipod touch - latest one - she started to input a passcode then didn't finish the process then turned off ipod. she turned it back on and it is asking for a passcode - she doesn't remember what she typed. Ipod is now disabled for one hour. Can we override the disable. How do we reset passcode when we don't klnow the original. It has never been synced to Itunes. I am completely lost.
If You Are Locked Out Or Have Forgotten Your Passcode
iTunes 10 for Mac- Update and restore software on iPod, iPhone, or iPad
iPhone, iPad, iPod touch: Wrong passcode results in red disabled screen
iOS- Understanding passcodes
If you have forgotten your Restrictions code, then follow the instructions
below but DO NOT restore any previous backup. If you do then you will
simply be restoring the old Restrictions code you have forgotten. This
same warning applies if you need to restore a clean system.
A Complete Guide to Restore or Recover Your iDevice (if You Forget Your Passcode)
If you need to restore your device or ff you cannot remember the passcode, then you will need to restore your device using the computer with which you last synced it. This allows you to reset your passcode and re-sync the data from the device (or restore from a backup). If you restore on a different computer that was never synced with the device, you will be able to unlock the device for use and remove the passcode, but your data will not be present. Refer to Updating and restoring iPhone, iPad and iPod touch software.
Try restoring the iOS device if backing up and erasing all content and settings doesn't resolve the issue. Using iTunes to restore iOS devices is part of standard isolation troubleshooting. Restoring your device will delete all data and content, including songs, videos, contacts, photos, and calendar information, and will restore all settings to their factory condition.
Before restoring your iOS device, Apple recommends that you either sync with iTunes to transfer any purchases you have made, or back up new data (data acquired after your last sync). If you have movie rentals on the device, see iTunes Store movie rental usage rights in the United States before restoring.
Follow these steps to restore your device:
1. Verify that you are using the latest version of iTunes before attempting to update.
2. Connect your device to your computer.
3. Select your iPhone, iPad, or iPod touch when it appears in iTunes under Devices.
4. Select the Summary tab.
5. Select the Restore option.
6. When prompted to back up your settings before restoring, select the Back Up
option (see in the image below). If you have just backed up the device, it is not
necessary to create another.
7. Select the Restore option when iTunes prompts you (as long as you've backed up,
you should not have to worry about restoring your iOS device).
8. When the restore process has completed, the device restarts and displays the Apple
logo while starting up:
After a restore, the iOS device displays the "Connect to iTunes" screen. For updating
to iOS 5 or later, follow the steps in the iOS Setup Assistant. For earlier versions of
iOS, keep your device connected until the "Connect to iTunes" screen goes away or
you see "iPhone is activated."
9. The final step is to restore your device from a previous backup. If you do not have a
backup to restore, then restore as New.
Maybe you are looking for
-
How can we re-enable automatic login?
My husband likes to have automatic login, and has always used it on his laptop. The computer belongs to his employer; yesterday, it wouldn't accept his login at all, and when he got it back from IT an hour later, there was a new account on it (the IT
-
Link SAP PI 7.3 to SolMan 7.1 - error during managed system configuration
All, I installed my diagnostics agent twice with different options: - Direct P4 connection via Java EE Dispatcher Node with port 5xx04 - P4 connection via SCS message server with port 81xx In both cases I get an error during the managed system config
-
IPod 5G Will Not Display iTunes Videos (Must Restart), All Photos Distorted
I own a 30GB iPod 5G which has never worked satisfactorily after I purchased the unit last year. In fact, after several trips last year to the Genius Bar at the Apple 5th Avenue store in New York, Apple replaced my unit with a new (or refurbished) mo
-
Cannot call Siebel UCM Organization service from SOA 11g
Hi, I am trying to call Siebel UCM Organization service from SOA 11g and getting the following error. Unable to process SOAP Header child element 'wsse:Security' with 'mustUnderstand="1"'(SBL-EAI-08000) Please let me know if anybody has solution for
-
Flickering cursor in form?
Hi all, in some of the forms I've been creating,when I mouse over and then out of a field, it sputters/flickers my cursor back and forth between the hourglass and pointer. Why does this happen, and how can I ultimately stop it? Thanks for any advice