QUERYING MULTIPLE TABLES
Hello,
Please considere these table below
PATIENT TABLE
PNO,PNAME,TITLE,DOB,CHILDREN,GP
p3,mansell,mr,23-May-61,2,Dr.Williams
p7,dury,mrs,05-Jun-64,0,Dr.Taylor
p2,currie,mrs,13-Jan-55,3,Dr.Thatcher
p8,gooch,mr,12-Apr-53,1,Dr.Spock
p4,gooch,mrs,03-Jun-59,1,Dr.Spock
p1,minogue,miss,03-Aug-69,0,Dr.Williams
DOSE
PNO,DNO,DOSEDATE,QTY
p4,d5,01-Feb-02,5
p2,d6,12-Jul-02,3
p4,d5,10-Sep-02,5
p1,d1,02-Oct-02,3
p7,d1,20-Oct-02,6
p8,d7,05-Nov-02,2
p4,d6,30-Nov-02,2
p4,d7,02-Jan-02,8
p1,d7,03-Mar-03,6
p4,d2,01-Apr-03,3
p1,d6,05-May-03,2
p8,d2,31-May-03,1
p4,d1,05-Jun-03,6
DRUG
DNO,DNAME,UNIT,DOI,COST
d1,sweet dreams,tab,20-Apr-87,0.15
d2,bliss,mg,12-Mar-91,5.00
d5,fly high,mg,10-Jul-88,1.89
d7,split,tab,04-Sep,90,0.90
d6,slow down,gm,05-Aug-89,1.66
What query statement will give me all patients who have been given the drug named ‘slow down’?
Something like
SELECT p.pname
FROM patient p
WHERE EXISTS( SELECT 1
FROM dose, drug
WHERE dose.dno = drug.dno
AND dose.pno = p.pno
AND drug.dname = 'slow down')should work.
Justin
Similar Messages
-
Hyperion Explorer 8.3 querying multiple tables that contain a specific item
I have 3 annual tables that contain data for 3 different years. Each table has a sale amount, item sold, and customer ID. I want to pull a specific customer ID from all 3 tables at once.
Is there a way to achieve this?
Thanks!
JohnnyAdd the 3 fields from the first table, then click Query > Append Query, then add the same 3 fields in the same order from the second table, then add the same 3 fields in the same order from the third table. This creates a UNION between the three tables; which means they need to be in the same order and have the same datatype.
If you want to show duplicate data found in the different sources, just change the UNION operator to a UNION ALL operator, otherwise it will suppress any duplicate rows.
To limit the data to one specific customer ID, you can set a limit on each of the UNION tabs with 'Customer ID = <selection>'.
Good luck!
Jarod Vierstra -
Need help querying multiple tables...
Afternoon...
I'm brand new to crystal, with literally 1.5 hours at most under my belt.
Some how during company restructuring CR got thrown on my plate.
I just built a report that pulls aged data from our call center's DB (We're running BMC Remedy for call tracking stored on a UNIX, Oracle 9i box)
What I am trying to do is select and sum time values in another table, base on the record selection for the current table.
The record selection is:
{CSG_ENTERPRISE_LOOKUP.Account_Number} like "033CDCO*" and
{CSG_ENTERPRISE_LOOKUP.Create_Date} in Aged0To30Days
I added and linked to another table by an enterprise record id. I'd like to grab all records from CSG_Join_Outer_Incident__to_Ticket that have "description LIKE "Incoming%" OR description LIKE "Outgoing%"" where the enterprise ticket numbers match. It should take the times of all records found, then sum and report them to the report as RPT_Total_time.
I haven't been able to find a solution to do this... I thought about a Union, or the following query:
select sum(Total_Time) from CSG_Join_Outer_Incident__to_Ticket where CSG_ENTERPRISE_LOOKUP."Escalation__Tkt_ID" = CSG_Join_Outer_Incident__to_Ticket."Escalation__Tkt_ID" and (CSG_Join_Outer_Incident__to_Ticket."Description" LIKE 'Incoming%' OR CSG_Join_Outer_Incident__to_Ticket."Description" LIKE 'Outgoing%') as RPT_Total_Time
Crystal does like anything I'm doing... I can't find anything of use on the web... and XI, which I have will not run on our reporting server that this report runs on (8.5)
Ideas? Suggestions?
Thanks.Look at hte JTable API. You'll find a link to the tutorial.
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html -
Cursor FOR UPDATE OF when querying multiple tables.
When I run the below code I am able to update the required table:
DECLARE
CURSOR cur_get_recs1 IS
SELECT *
FROM ncotestaging os
WHERE os.ote_status = 1
AND os.action_type = 'A'
FOR UPDATE OF ote_status;
BEGIN
FOR recOTEstage IN cur_get_recs2
LOOP
dbms_output.put_line('Updating Row from ' || recOTEstage.ote_status || ' to: 2');
UPDATE ncotestaging
SET ote_status = 2
WHERE CURRENT OF cur_get_recs2;
END LOOP;
END;
/Results as expected on my 5 rows...
SQL> @test.sql
Updating Row from 1 to: 2
Updating Row from 1 to: 2
Updating Row from 1 to: 2
Updating Row from 1 to: 2
Updating Row from 1 to: 2However, when I update the Cursor to the following....
CURSOR cur_get_recs1 IS
SELECT os.*, ces.customer_ref, ces.product_code
FROM ncotestaging os,
custRefSource ces
WHERE os.ote_status = 1
AND os.action_type = 'A'
AND ces.ref_source = os.service_code
FOR UPDATE OF ncotestaging.ote_status;I get the following error...
SQL> @test.sql
FOR UPDATE OF ncotestaging.ote_status;
ERROR at line 18:
ORA-06550: line 18, column 26:
PL/SQL: ORA-00904: "NCOTESTAGING"."OTE_STATUS": invalid identifier
ORA-06550: line 12, column 9:
PL/SQL: SQL Statement ignored
ORA-06550: line 25, column 54:
PLS-00364: loop index variable 'RECOTESTAGE' use is invalid
ORA-06550: line 25, column 9:
PL/SQL: Statement ignoredI don't know why the FOR UPDATE statement reports an invalid identifier. I seem to have the syntax correct according to the PL/SQL documentation. Any pointers gratefully received.CURSOR cur_get_recs1 IS> SELECT os.*, ces.customer_ref, ces.product_code
> FROM ncotestaging os,
> custRefSource ces
> WHERE os.ote_status = 1
> AND os.action_type = 'A'
>AND ces.ref_source = os.service_code
>FOR UPDATE OF ncotestaging.ote_status;
the problem iis u have the alias for the table 'ncotestaging' as os that's y it's throwing the error -
1. How to create an explain plan with rowsource statistics for a complex query that include multiple table joins ?
When multiple tables are involved , and the actual number of rows returned is more than what the explain plan tells. How can I find out what change is needed in the stat plan ?
2. Does rowsource statistics gives some kind of understanding of Extended stats ?You can get Row Source Statistics only *after* the SQL has been executed. An Explain Plan midway cannot give you row source statistics.
To get row source statistics either set STATISTICS_LEVEL='ALL' in the session that executes theSQL OR use the Hint "gather_plan_statistics" in the SQL being executed.
Then use dbms_xplan.display_cursor
Hemant K Chitale -
Count number rows in multiple tables from one query
Hi
I was wondering if its possible to have a single query return the number of lines in multiple tables, for example i have the tables
foo1
pk_foo1
and
foo2
pk_foo2
They are not joined together by any contraints. So the pseudo code for the query would be something like
SELECT numrows(pk_foo1), numrows(pk_foo2) FROM foo1, foo2
Thanks!without a join you get a cartesian product for the query:
SQL> select count(d.deptno),count(e.deptno)
2 from dept d,emp e
3 /
COUNT(D.DEPTNO) COUNT(E.DEPTNO)
105 105so you need to do a bit of trickery
1 select a.cnt,b.cnt
2 from
3 ( select count(d.deptno) cnt from dept d ) a,
4* ( select count(e.deptno) cnt from emp e) b
SQL> /
CNT CNT
7 15
SQL> select count(*) from dept;
COUNT(*)
7
SQL> select count(*) from emp;
COUNT(*)
15 -
BaseTableName blank when calling GetSchema on a query with multiple tables
I am using ODP.NET 11.2.0.3.0 and when calling GetSchemaTable on a DataReader that contains a join the returned SchemaTable has the BaseTableName and BaseColumnName fields blank - this is different than what I see with the Oracle OLE DB Provider and with how SQL Server's native provider works. I can't find any discussion of this - is this on purpose or is it a bug? why does the available schema information vary so drastically between a single table query and a query with multiple tables joined?
Thanks,
Bryan HintonHi Bryan,
I am also facing the same issue. Did u find any work around or any suggestions will be well appreciated.
Thanks,
Naresh. -
Hey All!
It's been a while since I last posted a message in these
forums. But it looks like I need your help again.
So here is the problem:
I have to create a list of the companies' projects, yet to
compile the complete list I have to query 4 tables, with a one to
many and many to many relation ship.
Here is what I have so far.
the main table is the projects table, hence I start with
that. Right now I can query the table, plus the companies table
that each project is linked to. Also, each project may have a link
to multiple companies, so I normalized the data by creating a
companies link table:
SELECT projects.project_id, project.project_name,
compproj_link.company_id
/* I only get the company id and convert it to an actual
name when I output */
FROM projects LEFT JOIN compproj_link ON
compproj_link.project_id = projects.project_id
/* here I also filter to get only active projects */
WHERE project.status in(1,2)
/* I group by the project id since there might be several
companies linked to a specific project */
GROUP BY projects.project_id, project.project_name,
compproj_link.company_id
ORDER BY project_name
This works perfectly fine when I output with the group
attribute, but now I have to link another table... called the
airdates. The reason is that I want to order my list by the
contents of this table (which may or may not be present)...
this airdates that is linked to my projects is structured
like so:
airdates
airdates_id - auto num
project_id - the project it is linked to hence could be
linked to many projects
then there are the actual air dates
airdateslist
airdateslist_id auto num
airdates_id - since for each air date record could be
multiple dates
airdate_date - date field
airdate_backupdate - another date field
airdate_current - this is a yes/no, and specifies whether
this date is most current.
Hence, by doing two more LEFT OUTER JOINS in my main query
would work fine, BUT I need to get the most current date from the
airdateslist that is set for a particular project. and when I do
this I get no records because as of yet, no project has an airdate
that is current.
So my question is if I can somehow add those airdates tables
to my main query, and be able to sort by the current date, IF it is
present, and if not, still have all my projects displayed?
PS. I think I have confused myself even more when writing
this out, so if you have any questions please write. Thank you in
advance!
Vega...First, this:
* I group by the project id since there might be several
companies linked to a specific project */
GROUP BY projects.project_id, project.project_name,
compproj_link.company_id
doesn't accomplish anything.
Second, when I read what you posted about the two airdates
tables, I'm not convinced that the table structure achieves what
the comments and fieldnames describe as the objective.
You say none of your projects have a current airdate. Do
these tables have any data at all? If not, it's going to be hard to
write a query when you can't ensure you got the correct
results. -
Dbms_xmlgen.newcontext query from multiple tables and ||
I have two questions
How do I get a dbms_xmlgen.context to query from multiple tables? I have been able to make it work with using one table only, but not with multiple tables.
And how to get the || (concat) to work within my query for my output to an xml file?
Here is my current query:
create or replace function get_xml return clob is
result clob;
qryctx dbms_xmlgen.ctxHandle;
SELECT DBMS_XMLGEN.getxml('select prefix, suffix, fiscal_yr
FROM rcv.recv_accessions ra
where ra.prefix = 8 and ra.fiscal_yr = 11')xml into result FROM dual;
result := DBMS_XMLGEN.getXML(qryCtx);
This is what I desire:
SELECT DBMS_XMLGEN.getxml('select ra.prefix||'-'|| ra.suffix||'-'|| ra.fiscal_yr accession, ss.date_in, st.test
FROM rcv.recv_accessions ra, ser.sero_samples ss, ser.sero_tests st
where ra.prefix = 8 and ra.fiscal_yr = 11 and ss.raid = ra.id and st.ssid = ss.id')xml into result FROM dual;
On this both the reference to multiple tables and the concat function cause errors.
Thank you
Edited by: user583094 on Mar 2, 2011 3:36 PMHi,
for the concat do I use xmlconcat?No, XMLConcat is used to concatenate XMLType fragments.
The || operator will do fine, but you must escape any single quote inside the string :
SELECT DBMS_XMLGEN.getxml(
'SELECT ra.prefix ||''-''|| ra.suffix ||''-''|| ra.fiscal_yr as accession,
ss.date_in,
st.test
FROM rcv.recv_accessions ra,
ser.sero_samples ss,
ser.sero_tests st
WHERE ra.prefix = 8
AND ra.fiscal_yr = 11
AND ss.raid = ra.id
AND st.ssid = ss.id'
INTO result
FROM dual;Or, use the quoting operator to define a custom string delimiter :
SELECT DBMS_XMLGEN.getxml(
q'{SELECT ra.prefix ||'-'|| ra.suffix ||'-'|| ra.fiscal_yr as accession,
ss.date_in,
st.test
FROM rcv.recv_accessions ra,
ser.sero_samples ss,
ser.sero_tests st
WHERE ra.prefix = 8
AND ra.fiscal_yr = 11
AND ss.raid = ra.id
AND st.ssid = ss.id
INTO result
FROM dual;BTW, a good practice would be to use bind variables for the query. DBMS_XMLGEN can handle them nicely :
CREATE OR REPLACE FUNCTION get_xml
RETURN CLOB
IS
qryctx DBMS_XMLGEN.ctxHandle;
v_out CLOB;
qrystr VARCHAR2(4000) :=
'SELECT ra.prefix ||''-''|| ra.suffix ||''-''|| ra.fiscal_yr as accession,
ss.date_in,
st.test
FROM rcv.recv_accessions ra,
ser.sero_samples ss,
ser.sero_tests st
WHERE ra.prefix = :b_prefix
AND ra.fiscal_yr = :b_fiscal_yr
AND ss.raid = ra.id
AND st.ssid = ss.id';
BEGIN
qryctx := DBMS_XMLGEN.newContext(qrystr);
DBMS_XMLGEN.setBindValue(qryctx, 'b_prefix', '8');
DBMS_XMLGEN.setBindValue(qryctx, 'b_fiscal_yr', '11');
-- to generate empty elements if necessary :
DBMS_XMLGEN.setNullHandling(qryctx, DBMS_XMLGEN.EMPTY_TAG);
v_out := DBMS_XMLGEN.getXML(qryctx);
DBMS_XMLGEN.closeContext(qryctx);
RETURN v_out;
END; -
Mysql query (search multiple tables in database)
I have 12 tables in a database - january through to december.
I need to search all 12 tables for 'keyworrd' phrases submitted by the user through a search form.
Must be a more streamlined way of doing it than below using 'UNION'. I have incorporated 2 tables in the below query but I need a more 'condensed' query for all 12 tables?
$sql = ('SELECT * FROM january WHERE tourTitle = "'.$keyword.'" UNION SELECT * FROM february WHERE tourTitle = "'.$keyword.'"');
Cheers
Osbregent wrote:
>That's what I did last year but thought I'd break it down this year into 12 easier to work with tables.
No, Ben is correct. Using 1 table for each month is absolutely the wrong way. It violates basic rules of normalization and causes all sorts of problems.
>Breaking it down appeals to be more so I can keep all the relevant months
>together instead of potentially becoming scattered throught-out one table.
That's what you use the Order By clause for.
>If by any chance the client says they want to update x, y or z I can go
>straight to the month in question without the necessity to flip through
>dozens of pages in phpMyAdmin as there is no real CMS management in place for this process.
Not sure what you are saying. Performing inserts, updates and queries is much simpler using a single table.
Whenever someone asks for a way to search through multiple tables, it tells me that the data structure is not designed well.
When I did this job last year there was about 60 pages created in phpMyAdmin. The records for January could be anywhere on those 60 pages as I may have to add additional records much later on in the process.
My thinking behind this was to keep all the month entries together so I could view them easily in phpMyAdmin.
Now due to my lack of knowlege about phpMyAdmin it could be possible to create a query to show only the january entries, I suspect it can do this.
I agree it is a lot simpler using 1 table to select and search through BUT I need if the ocassion arises to be able to view all the january or february entries etc one after the other, not 10 on page 2 and 3 on page 7 and 5 more on page 47 of phpMyAdmin.
So i quess what I really need is to write a select query in phpMyAdmin which only shows the selected entries for the month requested. I have not done much investigation into what phpMyAdmin can do........so I suppose I need to.
EDITED:
Arrgh you see IT WAS SO SIMPLE:
SELECT * FROM `tours` WHERE month = "March"
It's because I'm frightened of the bloody thing in case I mess something up! -
How to update multiple tables using results from query
I'm a bit rusty on this stuff and am hoping for some help.
Table 1 is:
location_id, location_name
Table 2 is
location_id, employee_id and misc. other columns
Then there are multiple tables with associated data, keys being location_id and employee_id.
There are no established relationships.
Trying to come up with a process to change location_id for all employees assigned to a particular location.
It seems to me that the basics are
select employee_id from Table2 where location_id='xxxxxx'
Then take each employee_id returned and change their location_id in each of the other tables
I'm not clear on how to load the returned employee id's as variables and then loop through them.
ThanksThanks for the welcome. I'll read up on the rules now.
Below is the DDL for a couple of the tables.
Version = 11g
I would query the users table for all users with a certain site_id and then use them to update the site_id in the users table (and other tables)
-- DDL for Table USERS
CREATE TABLE "USERS"
( "USERID" VARCHAR2(8 BYTE),
"PASSWORD" VARCHAR2(50 BYTE),
"FIRST_NAME" VARCHAR2(50 BYTE),
"LAST_NAME" VARCHAR2(50 BYTE),
"SITE_ID" VARCHAR2(5 BYTE),
"ROLE_ID" VARCHAR2(1 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "SITES_DATA_TS"
CACHE ;
-- DDL for Table EMPLOYEE_PROFILE
CREATE TABLE "EMPLOYEE_PROFILE"
( "EMPLOYEEID" VARCHAR2(9 BYTE),
"PROGRAM" NUMBER,
"REQUIREMENT" NUMBER,
"JOBNUM" VARCHAR2(50 BYTE),
"STATUS" VARCHAR2(50 BYTE),
"PROGRAM_TYPE" VARCHAR2(50 BYTE),
"SITE_ID" VARCHAR2(5 BYTE),
"NUM_QUAL_TEST_ATTEMPTS" NUMBER(7,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "SITES_DATA_TS"
CACHE ; -
Pure SQL of Select query on multiple tables in DB Adapter
I am trying use pure sql approach for a custom sql query on multiple tables for a DB adapter by modifying toplink_mappings.xml. But i am not getting other tables in my xsd. Please help.
hi Ravi,
can you pls be a bit clear? what is this about? where you are using?
thanks,
sneha. -
Creating a tree query on multiple tables
I have been reading the following article:
http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/gennick_connectby.html#f1
The diagram 1b that the above links to shows a local government hierrachy structure stored in multiple tables. I am having a little difficulty understanding how you would write a query (using start with connect by syntax) to get the data displayed in a tree format??
ie: (spaces are being removed so replaced them with --)
state1
--county1
--county2
----township1
----township2
--county3
state2
state3
--county3
--county4hi, please post a sample data it would help us to further analyze. thanks.
here is some example that might help
NODE_DATA NODE_PAREN
CAR TRANSPORT
PLANE TRANSPORT
BIKE TRANSPORT
TRANSPORT
HONDA CAR
747-400 PLANE
MAZDA CAR
FOOD
FRUIT FOOD
VEGETABLE FOOD
SPINACH VEGETABLE
CARROT VEGETABLE
12 rows selected.
SQL> select substr(rpad(' ',decode(level,1,0,2,2,4),' ')||node_data,1,20) node_data
2 from myTreeData
3 start with node_parent is null
4 connect by node_parent = prior node_data;
NODE_DATA
TRANSPORT
CAR
HONDA
MAZDA
PLANE
747-400
BIKE
FOOD
FRUIT
VEGETABLE
SPINACH
CARROT
12 rows selected.
SQL> -
How to set aggregation rule (SUM) to a query which uses multiple tables
Hi,
I have a doubt like i have a query .i want to get the sum of few columns in that..how can i achieve it as it joins multiple tables . i am posting the query under this. please help me to resolve this. i need to get summation of column which is marked in bold . i am so sorry to post such a big query.. thanks in advance.
SELECT DISTINCT
SAS.ACCOUNT_MONTH_NO,
SAS.BILL_TO_MAJOR_SALES_CHANNEL,
SAS.BUS_AREA_ID,
SAS.CUST_NAME,
SAS.PART_NO,
SAS.PART_DESC,
SAS.PRODUCT_CLASS_CODE,
SAS.SUPER_FAMILY_CODE,
*SAS.NET_SALES_AMT_COA_CURR,*
*SAS.GROSS_SALES_AMT_COA_CURR*,
*SAS.SHIPPED_QTY*,
SAS.SRCE_SYS_ID,
GWS.SRC_LOCATION,
GWS.PART_CF_PART_NUMBER,
GWS.ANALYST_COMMENTS,
NVL(GWS.CLAIM_QUANTITY,0) AS *CLAIM_QUANTITY*,
GWS.CUSTOMER_CLAIM_SUBMISSION_DATE,
GWS.CLAIM_TYPE,
GWS.CREDIT_MEMO_NO,
NVL(GWS.CREDIT_MEMO_AMT,0) AS *CREDIT_MEMO_AMT*,
GWS.TRANS_CREATED_BY,
GWS.COMPONENT_CODE,
GWS.DATE_OF_THE_FAILURE,
GWS.DATE_PART_IN_SERVICE,
GWS.PROBLEM_CODE,
NVL(GWS.TOT_AMT_REVIEWED_BY_CA,0) AS *TOT_AMT_REVIEWED_BY_CA*,
GWS.REGION
FROM
SELECT
TO_CHAR(A.STATUS_DATE, 'YYYYMM') AS ACCOUNT_MONTH_NO,
A.LOCATION_ID SRC_LOCATION,
A.CF_PN PART_CF_PART_NUMBER,
A.ANALYST_COMMENTS,
A.CLAIM_QUANTITY,
A.CUST_CLAIM_SUBM_DATE CUSTOMER_CLAIM_SUBMISSION_DATE,
A.CLAIM_TYPE,
A.CREDIT_MEMO_NO,
A.CREDIT_MEMO_AMT,
A.CREATED_BY TRANS_CREATED_BY,
A.FAULT_CODE COMPONENT_CODE,
A.PART_FAILURE_DATE DATE_OF_THE_FAILURE,
A.PART_IN_SERVICE_DATE DATE_PART_IN_SERVICE,
A.FAULT_CODE PROBLEM_CODE,
A.TOT_AMT_REVIEWED_BY_CA,
A.PART_BUS_AREA_ID AS BUS_AREA_ID,
A.PART_SRC_SYS_ID,
C.CUST_NAME,
C.BILL_TO_MAJOR_SALES_CHANNEL,
P.PART_NO,
P.PART_DESC,
P.PRODUCT_CLASS_CODE,
L.REGION
FROM
EDWOWN.MEDW_BIS_DTL_FACT A,
EDWOWN.EDW_MV_DB_CUST_DIM C,
EDWOWN.EDW_BUSINESS_LOCATION_DIM L,
EDWOWN.EDW_V_ACTV_PART_DIM P
WHERE
A.PART_KEY = P.PART_KEY
AND A.CUSTOMER_KEY = C.CUSTOMER_KEY
AND A.LOCATION_KEY = L.LOCATION_KEY
AND A.PART_SRC_SYS_ID = 'SOMS'
AND A.PART_BUS_AREA_ID = 'USA'
AND C.BILL_TO_MAJOR_SALES_CHANNEL <> 'IN'
GWS,
SELECT
A.ACCOUNT_MONTH_NO,
A.BUS_AREA_ID,
A.NET_SALES_AMT_COA_CURR,
A.GROSS_SALES_AMT_COA_CURR,
A.SHIPPED_QTY,
B.BILL_TO_MAJOR_SALES_CHANNEL,
A.SRCE_SYS_ID,
B.CUST_NAME,
D.PART_NO,
D.PART_DESC,
D.PRODUCT_CLASS_CODE,
D.SUPER_FAMILY_CODE
FROM
SASOWN.SAS_V_CORP_SHIP_FACT A,
SASOWN.SAS_V_CORP_CUST_DIM B,
SASOWN.SAS_V_CORP_LOCN_DIM C,
SASOWN.SAS_V_CORP_PART_DIM D
WHERE
C.DIVISION_CODE = A.DIVISION_CODE
AND
B.B_HIERARCHY_KEY = A.B_HIERARCHY_KEY
AND
D.PART_NO = A.PART_NO
AND
A.SRCE_SYS_ID = 'SOMS'
AND
A.BUS_AREA_ID = 'USA'
AND
B.BILL_TO_MAJOR_SALES_CHANNEL <> 'IN'
SAS
WHERE
SAS.ACCOUNT_MONTH_NO = GWS.ACCOUNT_MONTH_NO(+)
AND SAS.BILL_TO_MAJOR_SALES_CHANNEL = GWS.BILL_TO_MAJOR_SALES_CHANNEL(+)
AND SAS.BUS_AREA_ID = GWS.BUS_AREA_ID(+)
AND SAS.PRODUCT_CLASS_CODE = GWS.PRODUCT_CLASS_CODE(+);thanks in advance
aswinYou get rid of the distinct.
You put sum() around your starred items.
You put all the remaining columns in a GROUP BY clause.
You hope that that none of the other tables has more than one row that matches the SAS table, which would cause you to count that row more than once. -
Complex Multiple Table Sum Query
Here's a doozy for you. It is a pretty large query (by my standards, anyway) that is pulling data from multiple tables to fill a GridView in ASP.NET. The query is independent of .NET, so I think this is the right place for this post.
Summary: Trying to get all of the data from the main table and the children tables, in addition to summing up the matching values from two children tables.
The main table is RA_INVOICES. Some of the children tables are RA_USERS, RA_STATUS, etc. The two tables I am having issues with are RA_SYSTEMINVOICES and RA_ADJUSTMENTINVOICES. The key is MAN_INVOICE_NUM. If there are no rows in either the System or Adjustment tables include MAN_INVOICE_NUM, I get nothing back from the query. Here is my current query (I removed any fields that are not joined in some way, except for the key):
SELECT RA_INVOICES.MAN_INVOICE_NUM, RA_CURRENCIES.CURRENCY, RA_STATUS.STATUS, RA_REGIONS.REGION, RA_REASONS.REASON, RA_USERS.EMAIL AS EXPR5, RA_USERS_2.EMAIL AS EXPR4, RA_USERS_1.EMAIL, NVL(SUM(RA_SYSTEMINVOICES.SYS_INVOICE_AMT), 0) AS EXPR2, NVL(SUM(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT), 0) AS EXPR3
FROM RA_INVOICES
INNER JOIN RA_CURRENCIES ON RA_INVOICES.CURR_ID = RA_CURRENCIES.CURR_ID
INNER JOIN RA_REASONS ON RA_INVOICES.REASON_ID = RA_REASONS.REASON_ID
INNER JOIN RA_STATUS ON RA_INVOICES.STATUS_ID = RA_STATUS.STATUS_ID
INNER JOIN RA_REGIONS ON RA_INVOICES.USER_GROUP_ID = A_REGIONS.REGION_ID
INNER JOIN RA_USERS ON RA_INVOICES.CC_EMAIL_ID = RA_USERS.USER_ID
INNER JOIN RA_USERS RA_USERS_1 ON RA_INVOICES.CCM_EMAIL_ID = RA_USERS_1.USER_ID
INNER JOIN RA_USERS RA_USERS_2 ON RA_INVOICES.DCM_EMAIL_ID = RA_USERS_2.USER_ID
INNER JOIN RA_SYSTEMINVOICES ON RA_INVOICES.MAN_INVOICE_NUM = RA_SYSTEMINVOICES.MAN_INVOICE_NUM
INNER JOIN RA_ADJUSTMENTINVOICES ON RA_INVOICES.MAN_INVOICE_NUM = RA_ADJUSTMENTINVOICES.MAN_INVOICE_NUM
GROUP BY RA_INVOICES.MAN_INVOICE_NUM, RA_CURRENCIES.CURRENCY,
RA_STATUS.STATUS, RA_REGIONS.REGION, RA_REASONS.REASON, RA_USERS.EMAIL, RA_USERS_2.EMAIL, RA_USERS_1.EMAIL
Optionally I need to add the following:
HAVING (RA_INVOICES.MAN_INVOICE_NUM = 'xxxxxxxxxx')
So... where there are values in both of the tables (System and Adjustment) for MAN_INVOICE_NUM, I get results. Otherwise, if there are no tuples exist in one or both of those tables for MAN_INVOICE_NUM, I get nothing at all.
Sorry this is so complex. Thought I'd give you guys a good challenge. ;-)OK fellas (and ladies, if you happen to populate an Oracle board!)... one last question:
The solution offered worked perfectly. I would like to see if I can accomplish one last thing with this query, and that is to do some inline math operation on the results of the query. Basically, I need to take RA_INVOICES.MAN_INVOICE_NUM and subtract SUM(NVL(RA_SYSTEMINVOICES.SYS_INVOICE_AMT, 0)) AS SYSTOTAL and SUM(NVL(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT, 0)) AS ADJTOTAL from it.
I tried MAN_INVOICE_NUM - SYSTOTAL - ADJTOTAL AS TOTAL, but it returned "Error Message: ORA-00904: SYSTOTAL: invalid identifier."
So I changed the math to say MAN_INVOICE_NUM - SUM(NVL(RA_SYSTEMINVOICES.SYS_INVOICE_AMT, 0)) - SUM(NVL(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT, 0)), but I am afraid of the performance implications this has... it already read the value, why should I make it do it all over again? This query will eventuall be pulling a BUNCH of rows... a year from now we'll be in the tens of thousands if the user does a global query (most of the time this query will have a WHERE statement limiting the results). Just trying to make this query as efficient as possible.
The other alternative is to make this a SPROC. I'm clueless on SPROCS right now, but if I could gain a performance advantage using a SPROC, I'd rather do that.
Thanks in advance for your help!
Maybe you are looking for
-
Can't silence in and out of service sound
Every time I lose and/or get telephone service back, the phone makes a sound. My wife's (identical phone) does not. Can't find solution in manual. Help is appreciated, as this is annoying to me (and to others) especially in elevators! Thanks.
-
I have used Firefox for many years, about a week before Christmas I tried to used Sky Go for the 1st time in about 6-8 weeks and it wouldn't work. It was as if there was no player at all - no buffering, no error messages, just a white background box
-
Prevent Double click in Document Flow
Hello, We have a need in our project to restrict certain users from veiwing price in Sales Documents. We have achived this by using various exits and hiding the price. But we have a problem regarding the Document flow. When the user clicks on the doc
-
How Crystal represents currency
Crystal Reports XI When you tell crystal to convert number to Currency, is the result represented as a floating point number? I'm trying to figure out if I have to worry about rounding error when taking the sum of a field formula that has a value lik
-
Error when trying to add photos
I got a new ipod for Christmas and when I tried to add my photos I am getting an error message. I have a gateway laptop, I can add music, but not photos. The message is Ipod cannot be synced. An unknown error occurred(-50). But I can get my music.