Sum columns of different record count in joined tables
I have a problem with a query, please help.
I have two tables:
create table rec_a (key_code varchar(20),
TOT_AMT varchar(20),
INV_AMT varchar(20))
create table rec_B (key_code varchar(20),
INVOICE_AMT varchar(20),
PAID_AMT varchar(20))
insert into REC_A values (123123, 1168182.16, 1168182.16);
insert into REC_B values (123123, 205699.04,205699.04);
insert into REC_B values (123123,130912.78,130912.78);
insert into REC_B values (123123, 81622.87,81622.87);
insert into REC_B values (123123, 438032.43,438032.43);
insert into REC_B values (123123, 159936.17,159936.17);
insert into REC_B values (123123, 151978.87,151978.87);
table 1
KEY_CODE TOT_AMT INV_AMT
123123 1168182.16 1168182.16
table 2
KEY_CODE INVOICE_AMT PAID_AMT
123123 205699.04 205699.04
123123 130912.78 130912.78
123123 81622.87 81622.87
123123 438032.43 438032.43
123123 159936.17 159936.17
123123 151978.87 151978.87
I wrote a query to sum up all the fields (tot_amt,inv_amt,invoice_Amt,paid_amt)
SELECT B.key_code,sum(A.invoice_amt),sum(a.paid_amt),SUM(b.tot_Amt),SUM(b.inv_amt) FROM rec_a B, rec_b A WHERE A.KEY_CODE=B.KEY_CODE AND B.KEY_CODE in ('123123')
group by B.key_codeI got this:
KEY_CODE SUM(A.INVOICE_AMT) SUM(A.PAID_AMT) SUM(B.TOT_AMT) SUM(B.INV_AMT)
123123 1168182.16 1168182.16 7009092.96 7009092.96
But I expected this
KEY_CODE SUM(A.INVOICE_AMT) SUM(A.PAID_AMT) SUM(B.TOT_AMT) SUM(B.INV_AMT)
123123 1168182.16 1168182.16 1168182.16 1168182.16
Can anyone help me here?
Thanks
Edited by: 1003064 on Apr 29, 2013 3:19 AM
Hi,
welcome to the forum.
Please read SQL and PL/SQL FAQ
Particularly post CREATE TABLE and INSERT statement, describe the logic and post your expected output.
When you put some code and/or output please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
It's also considered a good practice to mark questions as answered when the answers are satisfying your question or provide additional details.
How does rec_a and rec_b tables relates to table1 and table2?
It seems that yours is a very simple error. When you join 2 tables all the common rows get repeated.
So without grouping your table will have something like this:table 1 table 2
KEY_CODE TOT_AMT INV_AMT KEY_CODE INVOICE_AMT PAID_AMT
123123 1168182.16 1168182.16 123123 205699.04 205699.04
123123 1168182.16 1168182.16 123123 130912.78 130912.78
123123 1168182.16 1168182.16 123123 81622.87 81622.87
123123 1168182.16 1168182.16 123123 438032.43 438032.43
123123 1168182.16 1168182.16 123123 159936.17 159936.17
123123 1168182.16 1168182.16 123123 151978.87 151978.87
Now sum up all the columns and you will understand why you get that result.
Regards.
Al
Regards.
Al
Edited by: Alberto Faenza on Apr 29, 2013 12:17 PM
Similar Messages
-
Count(*) giving different record count than Group by
I have a table which is giving me different record counts as below:
SELECT COUNT(1) FROM tbl_A --45104 records
SELECT ID,COUNT(*) FROM tbl_A GROUP BY ID ORDER BY 1 --42084 records(ID is the primary key)
Any idea why this will happen?Can you quickly show us what the below are returning?
SELECT COUNT(ID) FROM tbl_A
SELECT ID,COUNT(ID) FROM tbl_A GROUP BY ID ORDER BY 1 -
Get records count of all tables
Hi ,
I am trying to get the record count of all tables using dynamic query. I don't know how to put the value in placeholder. I tried the below code.
SET SERVEROUTPUT ON SIZE 1000000
DECLARE
CURSOR table_list
IS
select OBJECT_NAME from user_objects
where object_type in ('TABLE')
and object_name not like '%AUDIT_DDL%'
AND object_name not like 'MD_%'
AND object_name not like 'EXT_%'
AND object_name not like 'STG_%'
AND object_name not like 'SYS_%'
AND object_name not like 'TMP_%'
AND object_name not like 'TEMP_%'
order by 1;
v_count NUMBER :=0;
query_str VARCHAR2(1000);
BEGIN
FOR table_name IN table_list
LOOP
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME;
dbms_output.put_line(query_str);
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME );
v_count:= execute immediate query_str;
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME || ', Count ' || v_count );
END LOOP;
END;
I know I am doing wrong in the bold lines. But not sure how to fix it. Please help. Thanks in advance.Hi,
Welcome to the forum!
What you posted is basically right, assuming you really want to do dynamic SQL t all.
The only problem with
961618 wrote:
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME; would be if the object name included special characters (such as single-quotes) or lower-case letters. To avoid any possible problems, I would put the object name inside double-quotes:
... query_str := 'SELECT COUNT (*) FROM "' || table_name.OBJECT_NAME
|| '"';
v_count:= execute immediate query_str;
The correct syntax is
execute immediate query_str INTO v_count;V_count will be the number of rows in a single table. Keep another variable (say total_v_count) that keeps the total count so far.
Do you really need dynamic SQL?
SELECT SUM (num_rows) AS total_rows
FROM user_tables
WHERE table_name NOT_LIKE '%AUDIT_DDL%
AND ...
;gets the same information, accurate as of the last time statistics were gathered, and some of the numbers may be approximate. Depending on how you use the results, that may be good enough for you. If you actually have 10,000,123 rows, and the query says you have 10,000,000, does it really matter? -
Sum columns in different groups
Hi Alll,
I have created 4 queries. In all quries rmng column is there. It is printed like
group1 group2 group3 group4
rmng1 rmng2 rmng3 rmng4
3 2 4 5
6 7 10 11
I need to calculate rmng columns and put it into tot rmng column like
group1 group2 group3 group4
rmng1 rmng2 rmng3 rmng4 totrmng(rmng1+rmng2+rmng3+rmng4)
3 2 4 5 14
6 7 10 11 34
How to do in reports? Can you please tell me the solution?
Thanks,
Annhi Ann,
Virtual Column:_
Try the below in your table,
Alter table <TabName> add (totrmng as (rmng1+rmng2+rmng3+rmng4));
and then just add the newly added column in your query to achieve the needs.
Regards,
Navin Kumar G -
Record count in internal table
i want to know record count for the records stored in
internal table.
do we have any system field to display record count?Hi,
Try this:
Data: count_lines type i.
describe table my_table lines count_lines.
Regards,
Arjan -
Query to display all records count of all tables in a schema
Hi,
I need to count all the records of all my tables in a certain schema and display the max amount of the record count. Do you have a script for this one??SQL> create function countrec(in_tab in varchar2) return number is
2 retval number;
3 begin
4 execute immediate 'select count(*) from '||in_tab into retval;
5 return retval;
6 end;
7 /
Function created.
SQL> select table_name, countrec(table_name)
2 from tabs;
TABLE_NAME COUNTREC(TABLE_NAME)
QUERY_TOOL_DATA_COLLECTION 5
TEST01 0
T1 14
EMP 14
SALGRADE 5
FILES 0
PROVA 0
TEST 0
T_MASTER 1
T_CHILD 3
TAB_ONE 30
TAB_TWO 10
A 3
B 4
C 3
D 3
BONUS 0
DEPT 4
18 rows selected.Max -
Record counts of the tables in USER_TABLES
Hello everyone.
Please give me advice, is it possible to enumerate the tables in the USER_TABLES and in the same time to retrieve the record count in every each of them?
To illustrate, I want something like that:
select t.table_name,(select count(*) from t.table_name) from USER_TABLES t
This is only for isllustration. I know that is not the way.
Thank you in advance for your answers.Code could be compacted down a little...
SQL> set serveroutput on
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor cur_table_count is
3 select table_name from user_tables order by table_name;
4 v_cnt number;
5 begin
6 dbms_output.put_line('Table Name Record Count');
7 dbms_output.put_line('============================== ============');
8 for t in cur_table_count
9 loop
10 execute immediate 'select count(*) from '||t.table_name into v_cnt;
11 dbms_output.put_line(RPAD(t.table_name,31)||v_cnt);
12 end loop;
13* end;
SQL> /
Table Name Record Count
============================== ============
BONUS 0
DEPT 4
EMP 14
SALGRADE 5
PL/SQL procedure successfully completed. -
How to compare record count of two tables?
Hi,
i am in need of simple sql script where i can compare two table record count.
i have something like below:
(select count(*) from table1) minus (select count(*) from table2)
now the problem is if the table1 count greater then table2 count the output is fine.
If the table2 record count is more then i am getting zero as the output.
how can i get the difference in two tables record count?
Thanks a lot in advance.
--Raman.Doing a MINUS between the counts does not yield the diff.
e.g. if table A has 100 records and table B has 70 records then,
SELECT count(*) FROM A
minus
SELECT count(*) from B
will give 100 and not 30.
Try this:
SELECT (
CASE WHEN ((select count(*) cnt from A) - (select count(*) cnt from B)) <0
THEN ((select count(*) cnt from A) - (select count(*) cnt from B))* -1
ELSE ((select count(*) cnt from A) - (select count(*) cnt from B)) END) Difference
FROM dualor this is simpler
SELECT abs(((select count(*) cnt from A) - (select count(*) cnt from B))) difference FROM dualEdited by: Caitanya on Jan 9, 2009 7:12 AM
Applied abs function after seeing BluShadow's post :) -
Fetching Columns as different RECORDS
HI,
I have a problem. In my application, i have a table as
Table
Column1
Column2
Column2
suppose table has one record ( cat , dog , mouse )
MY requirement is..i need to fetch data from this table in a way that every query fetch each column as a DIFFERENT ROW for example
when i query , i should get
record one-- cat
record 2-----dog
record 3-----Mouse
how can i do this...avoiding use of UNION.select column1||chr(10)||column2||chr(10)||column3 from table_name
-
File to Jdbc: how to get record count from DB table
Hello,
i have a scenario file to JDBC....ihave to insert input file data to DB table.
now my requirement is ..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
i think following options:
1. in mapping write lookup to call JDBC sender channel and fetch count and map same to target filed of DB. if this is ok...please provide UDF code..2. db triggers (not suitable for my req.)
So kindly let meknow possible solutions and required UDF codes..please
Thanks in advance...SARAN>>>..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
i think following options:
Suggestions:
1)Create an id column in db table. Talk to DB guy to create oracle sequencer for that column. So, every time you insert record that field will be updated with oracle sequencer. You dont need to handle this.
Refer this link
http://www.techonthenet.com/oracle/sequences.php
2) If you want to handle via pi, following suggestions..
If you use PI 7.1 or above, use jdbc lookup in the mapping and do the query something like this
Refer this link
/people/jin.shin/blog/2008/02/15/sap-pi-71-mapping-enhancements-series-graphical-support-for-jdbc-and-rfc-lookups
Do select query as below
select count(*) from tablename;
the above query will return number of rows exist in the table. So use that value and map it in the target field.
If you use pi 7.0 or below then use the previous reply and do the UDF implementation for jdbc lookup during mapping. Because jdbc lookup does not support in those versions.
Hope that helps.
Baskar -
How to maintain previous and record count in audit table in SQL Server 2008 r2?
Hi Experts ,
Situation :
in our database we are having few of stored procedures which will drop and recreates the tables and it is scheduled on weekly basis. when this job will run all the stored procedures will drop all the tables and recreate. Now we need to create one table which
will maintain history of the records.
my table structure is listed below
TableName CurrentReocrdCount CurrentExecutionDate PreviousReordCount PreviousExurtiondate
TEST 1000 2014-03-30 NULL NULL
Test 1500 2014-04-10 1000 2014-03-30
Test 2000 2014-04-11 1500 2014-04-10
How do i achive this .
franklinsentilYou need to create audit tables for these. The table will be populated by COUNT value inside stored procedure. Each time it clears the main table and fills new data and also logs count details to audit tables. You can use COUNT(*) to get count value
and GETDATE function to get current execution value.
So proc will look like
CREATE PROC procname
@param....
AS
--step to drop existing table
IF OBJECT_ID('tablename') IS NOT NULL
DROP TABLE <table name>
--step to fill new table
SELECT ...
INTO TableName
FROM
--Audit table fill step
INSERT AuditTable (TableName,CurrentRecordCount,CurrentExecdate,PrevRecordCount,PrevExecDate)
SELECT TOP 1 'TableName',(SELECT COUNT(*) FROM tableName),GETDATE(),CurrentRecordCount,CurrentExecDate
FROM AuditTable
ORDER BY CurrentExecDate DESC
UNION ALL
SELECT 'TableName',(SELECT COUNT(*) FROM tableName),NULL,NULL
WHERE NOT EXISTS (SELECT 1 FROM AuditTable)
GO
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Oracle 10g - Insert in to Temporary Table - Record count mismatch between s
We are trying insert records from a select query in to temporary table, some of the records is missing in the temporary table. The select statement is having multiple joins and union all which it little complex query. In simple terms the script contains 2 part 1st Part Insert in to temporary table 2nd part Select query with multiple joins, inline sub queries, unions and group by classes and conditions
Eg. If we execute select statement alone it returns some count for example => 60000 After inserting into the temp table, in temp table the count is around 42000 why is the difference?
It is simple bulk inserts... insert in to temp table select from xxx. also, there is no commit in between. The problem is all the records populated by the select statement are not inserted in to temp table. some records are not inserted.*
Also, we had some other observation. It only happens in its 2nd execution and not its first run. Hope there might be some cache problem
Even, we also did not believe that. We are wondering. In TOAD, we tested however at times it happens. In application jar file, after "insert in to temp select * from xxx" we take the i. record count of temp table and ii. record count of "select * from xxx" separately but both doesn't match. Match only at 1st time.
Thank you in advance for your efforts and help.
Shiva.The code looks like
sql = "insert in to temptable select x,y,z,.... from xxx,abc,pqr..where...."; (logial but not real is very complex around 700 lines with multiple joins, inline sub queries, group by etc. )
stmt = conn.createStatement();
rCount= stmt.executeUpdate(sql);
Actual issue is
rCount = xxxx = Count(temptable) < count(select x,y,z,.... from xxx,abc,pqr..where....)
why this diffference ? some records populated in the select but not inserted in to temp table
Anyone can explain? -
Sequence - Record count is double
Hi Experts,
I have requirement to move the data from from one table to another in Oracle.
I have created a sequence for autonumber and the same attribute has been defined as primary key as well and using IKM sql Control append.
When the data is being transfered to target table actually count is double or 3 times of origianl count.
Please suggest me how to resove this.
Regards,
PreetHi ,
Can you please check the operator log :- number of inserts for I$ table and main table.
And find which step is giving issue.
please copy that query here.
Other details needed :-
Source record count.
Target record count before execution
Target record count after execution
I$ record count
Any joins ?
Regards,
Rathish A M -
Record Count Issue in Search page ?
Hi Friends
I am trying to display record count on Search page and I have the following code in
The table has total of 62 Rows
AM : for testing purpose, i am printing in log
public void getISAGRecordCount()
OAViewObject vo = (OAViewObject)getXXG2_ELIM_ISAGSView1(); //getXXG2ISAGSearchVO1();
int fetchedRowCount = 0;
vo.setMaxFetchSize(-1);
vo.executeQuery();
fetchedRowCount = vo.getRowCount();
System.out.println("RowCount: "+ fetchedRowCount);
IN PFR of CO: I am calling by this way
am.invokeMethod("getISAGRecordCount");
the Issue is
for the first time, when i search Based on search criteria, I know it should dispaly 10 records but in the Log file i see the total Record Count of the Table Ex; 62
When i do the serach for the second time, based on search criteria, I know it should display 20 records, but the log file has 10 records ( previous search results)
If I do the search for 3rd time, I see 2nd search results in log
Any help in this issue, how to fix this?
Thanks
RaviHi,
Please donot use getRowCount(), use getFetchedRowCount() and remove setMaxFetchSize(-1).
Hope it will resolve your issue.
Just for understanding of the concept:
getFetchedRowCount() returns the number of rows cached in the view object -- including programmatically inserted rows.
The getRowCount() implicitly execute a query against the database (if a query has not been executed yet)
Regards,
Reetesh Sharma -
A sample code to check records of a system table?
hi ABAP4 experts,
We are pretty new at ABAP4. We would be appreciated if you can provide a sample code to check how many records and calculate a total amount for a specific field, e.g., DMBTR in a system table, e.g., BSEG. Note: there is no any selection for this table BSEG, we just want to get the total record count in this table and also the total amount for a specific field e.g. DMBTR in this table.
Do we have to use an internal table to transfer all the records of BSEG into the internal table to get the result?
We will give you reward points!Hi Kevin,
Using SUM directly in SQL will NOT work for table BSEG because BSEG is pool table. You will get an ABAP error.
"Aggregate functions and the addition DISTINCT are not supported in field lists for pooled and cluster tables".
You need an internal table to transfer all data from BSEG and perform calculation for count and sum.
Concerning about performance running perhaps you can code something like this.
REPORT ZZFLTEST NO STANDARD PAGE HEADING.
TABLES: BSEG.
DATA: CURS TYPE CURSOR,
PACKAGE_SIZE LIKE RMCS4-MC_CM_PSIZE VALUE '10000'.
DATA: BEGIN OF I_BSEG OCCURS 0,
BELNR TYPE BSEG-BELNR,
BURKS TYPE BSEG-BURKS,
GJAHR TYPE BSEG-GJAHR,
BUZEI TYPE BSEG-BUZEI,
DMBTR TYPE BSEG-DMBTR,
SHKZG TYPE BSEG-SHKZG.
DATA: END OF I_BSEG.
DATA: TOT_DMBTR TYPE BSEG-DMBTR,
TOT_REC TYPE I.
SELECTION-SCREEN BEGIN OF BLOCK B01 WITH FRAME TITLE TEXT-001.
SELECTION-SCREEN SKIP.
PARAMETERS: P_SIZE LIKE RMCS4-MC_CM_PSIZE DEFAULT '10000'.
SELECTION-SCREEN SKIP.
SELECTION-SCREEN END OF BLOCK B01.
START-OF-SELECTION.
PACKAGE_SIZE = P_SIZE.
OPEN CURSOR WITH HOLD CURS FOR
SELECT BELNR BURKS GJAHR BUZEI DMBTR SHKZG
FROM BSEG
WHERE BELNR <> SPACE
AND BURKS <> SPACE
AND GJAHR <> SPACE
AND BUZEI <> SPACE.
*Fetch internal table I_BSEG for every 10000 records.
DO.
FETCH NEXT CURSOR CURS
INTO TABLE I_BSEG PACKAGE SIZE PACKAGE_SIZE.
IF SY-SUBRC <> 0.
EXIT.
ENDIF.
ENDDO.
CLOSE CURSOR CURS.
LOOP AT I_BSEG.
TOT_REC = TOT_REC + 1.
IF I_BSEG-SHKZG = 'S'.
TOT_DMBTR = TOT_DMBRT + I_BSEG-DMBTR * -1.
ELSE.
TOT_DMBTR = TOT_DMBTR + I_BSEG-DMBTR.
ENDIF.
ENDLOOP.
WRITE: / 'TOTAL BSEG-DMBTR:', TOT_DMBTR,
/ 'TOTAL RECORD: ', TOT_REC.
END-OF-SELECTION.
Hope this will help.
Regards,
Ferry Lianto
Maybe you are looking for
-
Photoshop CS2 hogs RAM even when all the documents are closed.
Like the title says. I was able to re-create the issue in this video: (nevermind, I guess I can't post links) Long story short; after having documents open, I have to close Photoshop and re-open it to get my RAM back. Why does this happen? Thanks in
-
Is there a simple way to create a dvd from a sony handycam other than the iMovie? I find it comlicating to transfer the scenes from the camera and then how to make it work as a continious movie?
-
Hi Experts I am in to Intercompany STO process with one step Goods issue procedure. When i tried to post PGI for the NLCC type D.O obtained the below error. Error Message Fld selectn for mvmt type 645 / acct 6005100 differs for Business Area (033) Pl
-
LMS 4.2.3 Database Backup Issue
Hi All, I was unable to take database backup of the LMS. Its failing with the below error. Error :Backup Failed: Error(404) Insufficient space on destination Where on destination drive i have space of 150GB Free space. but still LMS throwing the err
-
Lost content of body after upgrade
Upgraded to maverics - no content in the body of mail - lost 1000's of emails - no duplicate boxes in the library - I look forward to retrieving... ahahahahhaha