How to Recursively Sum a Sum?
Sorry, everyone, this is driving me nuts. I have the following query, which gives me the relative percentage of [INDEX MARKET CAP].
SELECT *, [INDEX MARKET CAP] * 100/SUM([INDEX MARKET CAP]) OVER() as [%]
FROM [S&P_Emerging_SmallCap_(US_Dollar)]
So, I get a sum of the [INDEX MARKET CAP], and then find the relative percentage of each items in the INDEX MARKET CAP. Great! now, I'm trying to modify the query a bit to give me the SUM of each relative INDEX MARKET CAP. So, the sum will
be 100%! I just want to prove that the query works.
I'm trying to follow the example here.
http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx
It seems so simple, but this dang thing just won't work.
I think it should be something like this.
;With CTE (Company, [%])
AS
SELECT *, [INDEX MARKET CAP] * 100/SUM([INDEX MARKET CAP]) OVER() as [%]
FROM [S&P_Emerging_SmallCap_(US_Dollar)]
Select Company, SUM([%]) as Total
FROM CTE
Group By Company, Total
I keep getting this.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'SELECT'.
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.
Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. The garbage you
posted has spaces in it! That means that you cannot use those names in any ISO standard programming. You are an 1950's COBOL Programmer who does not understand tiered architectures, so he writes headers for display instead of having a presentation layer. In
fact, you are even worse with all that meta-data garbage in your data elements. USD is a unit of measurement on a scale, not part of a data element name. Is there any way you can get a book or course in basic data modeling??
Why do you think that “company” is a clear, precise data element name that is an industry standard? It is not! This generic, vague and useless. I would guess that you are using a ticker symbol or a DUNS as the identifier. But it might be “company_<anything>”
or worse. What is that generic “total”? Why did you destroy any hope of a data dictionary with crap like [%]?? First of all, we use double quotes in ANSI/ISO Standard SQL, so this disaster should have been “%” without the brackets. Why do you think you can
use that one character name anywhere else? What language? The best it could be is "generic_percentage", so that programmers that follow you will know it is crap. Pros write code for the maintenance guys that have not been hired yet, not for personal
spreadsheet use.
50 years ago when you were writing COBOL, there was a hierarchical record structure. In RDBMS, rows are not records and columns are not fields. The fields (attributes) are drawn from domains of scalar values. The names exist in those domains. Your automobile
is a VIN everywhere in the universe! It is not local.
Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
>> Sorry, everyone, this is driving me nuts. I have the following query, which gives me the relative percentage of [INDEX MARKET CAP].
SELECT *, [INDEX MARKET CAP] * 100/SUM([INDEX MARKET CAP]) OVER() AS "generic_percentage" FROM [S&P_Emerging_SmallCap_(US_Dollar)] <<
>> So, I get a sum of the [INDEX MARKET CAP], and then find the relative percentage of each items in the INDEX MARKET CAP. Great! now, I'm trying to modify the query a bit to give me the SUM of each relative INDEX MARKET CAP. So, the sum will
be 100%! <<
No, it will not. In fact, you will be lucky to get 99.99% -- do you understand rounding errors? Since you were rude (really, really rude by SQL Forum standard, in fact) We have no idea what data types we have here; we have to guess you used DECIMAL(s,p)
so you might get better answers with “index_market_cap * 100.0000 /SUM(index_ market_cap) OVER() AS index_market_cap_percentage”; See the decimal places? Unlike spreadsheet, we have to worry about this in SQL.
As far as your error goes, look at the CTE column list and the GROUP BY; they do not match !
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Similar Messages
-
How to calculate the individual sums of multiple columns in a single query
Hello,
Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
Will appreciate any help or suggestion.
Thanksuser13667036 wrote:
Hello,
Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
Will appreciate any help or suggestion.
ThanksLooks like you want a simple group by.
select
yr
, mnth
, region
, sum(handled_package)
, sum(expected_missing_package)
, sum(actual_missing_package)
from test
group by
yr, mnth, region
order by
yr, mnth, region;I wouldn't recommend storing your data for year / month in 2 columns like that unless you have a really good reason. I would store it as a date column and add a check constraint to ensure that the date is always the first of the month, then format it out as you wish to the client.
CREATE TABLE test
year_month date,
Region VARCHAR2(50),
CITY VARCHAR2(50),
Handled_Package NUMBER,
Expected_Missing_Package NUMBER,
Actual_Missing_Package NUMBER
alter table test add constraint firs_of_month check (year_month = trunc(year_month, 'mm'));
ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
2 Values (to_date('2012-nov-12', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
ERROR at line 1:
ORA-02290: check constraint (TUBBY.FIRS_OF_MONTH) violated
Elapsed: 00:00:00.03
ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
2 Values (to_date('2012-nov-01', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
1 row created.
Elapsed: 00:00:00.01
ME_XE?select
2 to_char(year_month, 'fmYYYY') as year
3 , to_char(year_month, 'fmMonth') as month
4 , Region
5 , CITY
6 , Handled_Package
7 , Expected_Missing_Package
8 , Actual_Missing_Package
9 from test;
YEAR MONTH REGION CITY HANDLED_PACKAGE EXPECTED_MISSING_PACKAGE ACTUAL_MISSING_PACKAGE
2012 November Western San Fransisco 200 10 5
1 row selected.
Elapsed: 00:00:00.01
ME_XE?Then you have nice a nice and easy validation that ensures you data integrity.
Cheers, -
Sum Encrypt does not recognize a copy of a file through linux to Mac 0S9. How decrypt this file with Sum Encrypt?
Hello, and welcome to Apple Support Communities!
I am not familiar with the program that you list, however files in OS 9 use things called Resource Forks (rather than file extensions) for filetype and creator.
If you sent a file through Linux these resource forks probably got stripped and now the file is nothing to your Macintosh.
It is best to BinHex your files (.hqx) before leaving the HFS file system so that their resource forks are preserved.
Regards,
Ryan -
How do I subtract one sum from another and show a balance in another box
In numbers how do I show the difference in total from one column and another as a balance amount?
=SUM(range_one)-SUM(range_two)
Details available in iWork Formulas and Functions User Guide.
Yvan KOENIG (VALLAURIS, France) samedi 9 juillet 2011 15:45:36 iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8
Please : Search for questions similar to your own before submitting them to the community
To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer ! -
How can I build a sum of two rows in a CNiReal64Matrix?
How can I build a sum of two rows in a CNiReal64Matrix?
You could copy the two rows that you want to add into two CNiReal64Vectors via CNiReal64Matrix::CopyRow, then add the two CNiReal64Vectors via CNiReal64Vector::Add or CNiReal64Vector:perator+.
- Elton -
How to find deptno wise sum(sal) using subquery
hi all,
how to find deptno wise sum(sal) using subquery.
can u tell me any one please.
thanks,
regards.If we are talking standard emp and dept tables ala scott schema then (say); -
select ename, sal, total_dept_salary
from emp,
(select sum(sal) as Total_Dept_Salary,
deptno
from empt
group by
deptno) saldept
where emp.deptno = saldept.deptno
Is that what you were after?? (I would advise against correlated sub-queries on all but the most modest of tables)
There are nicer ways of doing the subquery depending on which version of the db you are on... -
How to return the same SUM value from two tables
Hello,
I have the following data:
SQL> SELECT * FROM t1;
T1_ID T1_VALUE
1 500
1 500
SQL> SELECT * FROM t2;
T2_ID T2_VALUE
1 1000
SQL> SELECT t1_id, SUM(t1_value), SUM(t2_value)
2 FROM t1, t2
3 WHERE t1_id = t2_id
4 GROUP BY t1_id;
T1_ID SUM(T1_VALUE) SUM(T2_VALUE)
1 1000 2000How is it possible that SUM(T2_VALUE) returns also 1000.
Thank youHere's one way:
with t1 as (select 1 t1_id, 500 t1_value from dual union all
select 1 t1_id, 500 t1_value from dual),
t2 as (select 1 t2_id, 1000 t2_value from dual)
select t3.t3_id, t3.t3_sum, t4.t4_sum
from (select t1_id t3_id, sum(t1_value) t3_sum from t1
group by t1_id) t3,
(select t2_id t4_id, sum(t2_value) t4_sum from t2
group by t2_id) t4
where t3.t3_id = t4.t4_id -
The following query runs fine under 8.1.6 but returns bad result under 8.1.7.2 :
SELECT SUM(NBANOMALIE4), SUM(NBANOMALIE2)
FROM
(SELECT COUNT(*) "NBANOMALIE2" FROM CPN A, ANOCPN B WHERE A.CODENS= '128' AND B.CODANO='2' AND A.NUMFOR = B.NUMFOR ) ,
(SELECT COUNT(*) "NBANOMALIE4" FROM CPN A, ANOCPN B WHERE A.CODENS= '128' AND B.CODANO='4' AND A.NUMFOR = B.NUMFOR )
GROUP BY NBANOMALIE2, NBANOMALIE4;
Result given under 8.1.6 is
SUM(NBANOMALIE4) SUM(NBANOMALIE2)
1 0 (correct)
Result given under 8.1.7.2 is
0 0 (wrong)
if query is changed to "SELECT SUM(NBANOMALIE2), SUM(NBANOMALIE4) ..."
Result given under 8.1.7.2 is
1 1 (wrong too !)
actually the result given for ALL is the result of the last "SUM()" in the select ...
Is it a bug ? if so any patch ? Is there a workaround ?
Thanks for any help
Charlie [email protected]a solution was to use decode()
here is a workaround :
SELECT DECODE(B.CODANO,'2',1,0) NBANOMALIE2, DECODE(B.CODANO,'4',1,0) NBANOMALIE4
FROM CPN A, ANOCPN B
WHERE A.CODENS= '128' AND B.CODANO IN ('2','4') AND A.NUMFOR = B.NUMFOR;
I had it from http://www.orafaq.com/. ...
Charlie [email protected] -
Sum the sum of fields in crystal report
In crystal report 2008, i have rows of data grouped by document number. Sum of each document (RTotal1) display at Group Footer.
At the Report Footer level, I want to display the Grand Total. In formula workshop, I tried to add a formula to sum RTotal1 above. However, error message indicated 'this field cannot be summarized'.
Second try: In Running Total Fields, I tried to add RTotal1 above to the field but error message indicated 'invalid field selection'. Any idea what's the proper way to sum the sum of fields?You need to use a variable, create 3 formula
@reset
whileprintingrecords;
global numbervar GTotal:=0;
//place this in report header, or higher grou header as appropriate
@Eval
whileprintingrecords;
global numbervar GTotal:=GTotal + Sum( valuefield, groupfield);
// place this in group footer where your sum shows
@display
whileprintingrecords;
global numbervar GTotal;
//Place this in report or higher group footer
Ian -
Sum(misses)/(sum(gets)
Hi,
is it any way to combine all these :
select name, gets, misses,
immediate_gets, immediate_misses, sleeps
from v$latch
where name in ('redo allocation', 'redo copy')
set head off
select 'Ratio of MISSES to GETS: '||
round((sum(misses)/(sum(gets)+0.00000000001) * 100),2)||'%'
from v$latch
where name in ('redo allocation', 'redo copy')
select 'Ratio of IMMEDIATE_MISSES to IMMEDIATE_GETS: '||
round((sum(immediate_misses)/
(sum(immediate_misses+immediate_gets)+0.00000000001) * 100),2)||'%'
from v$latch
where name in ('redo allocation', 'redo copy')
Many thanks.I tried this
SELECT name, gets, misses,
immediate_gets, immediate_misses, sleeps, 'Ratio of MISSES to GETS: '||
round((sum(misses)/(sum(gets)+0.00000000001) * 100),2)||'%', 'Ratio of IMMEDIATE_MISSES to IMMEDIATE_GETS: '||
round((sum(immediate_misses)/
(sum(immediate_misses+immediate_gets)+0.00000000001) * 100),2)||'%'
FROM v$latch
WHERE name IN ('redo allocation', 'redo copy')
GROUP BY name, gets, misses,immediate_gets, immediate_misses, sleeps
but I have
query column #7 ('RATIOOFMISSESTOGETS:'||ROUND((SUM(MISSES)/(SUM(GETS)+0.00000000001)*100),2)||'%') is invalid, use column alias
Please help. -
How to set limit on sum of totals of all sales orders of a business partner in SAP B1
Hi,
I would like to set a limit on a business partner so that the sum of totals of all orders placed for that business partner do not exceed a certain amount. How can I do that?
Regards,
VictorHi,
Yes can set limit for Business partners. Follow the steps to achieve:
1. Choose "Credit limit" check box under Administration--->System Initialization--->General settings--->BP sub tab and choose sales order check box
2. Set credit limit for BP under Business partner master data--->Payments terms.
For complete information, you can refer SAP help file.
Thanks & Regards,
Nagarajan -
HOW TO IMPROVE PERFORMANCE ON SUM FUNCTION IN INLINE SQL QUERY
SELECT NVL(SUM(B1.T_AMOUNT),0) PAYMENT,B1.ACCOUNT_NUM,B1.BILL_SEQ
FROM
SELECT P.T_AMOUNT,P.ACCOUNT_NUM,P.BILL_SEQ
FROM PAYMENT_DATA_VIEW P
WHERE TRUNC(P.ACC_PAYMENT_DATE) < '01-JAN-2013'
AND P.CUSTOMER_NAME ='XYZ'
AND P.CLASS_ID IN (-1,1,2,94)
) B1
GROUP BY B1.ACCOUNT_NUM,B1.BILL_SEQ
Above is the query.If we run inner query it takes few second to execute but while we are summing up the same amount and bill_Seq using inline view, it takes time to execute it.
Note: Count of rows selected from inner query will be around >10 Lac
How to improve the performance for this query?
Pls suggest
Thanks in advance989209 wrote:
SELECT NVL(SUM(B1.T_AMOUNT),0) PAYMENT,B1.ACCOUNT_NUM,B1.BILL_SEQ
FROM
SELECT P.T_AMOUNT,P.ACCOUNT_NUM,P.BILL_SEQ
FROM PAYMENT_DATA_VIEW P
WHERE TRUNC(P.ACC_PAYMENT_DATE) < '01-JAN-2013'
AND P.CUSTOMER_NAME ='XYZ'
AND P.CLASS_ID IN (-1,1,2,94)
) B1
GROUP BY B1.ACCOUNT_NUM,B1.BILL_SEQ
Above is the query.If we run inner query it takes few second to execute but while we are summing up the same amount and bill_Seq using inline view, it takes time to execute it.
Note: Count of rows selected from inner query will be around >10 Lac
How to improve the performance for this query?
Pls suggest
Thanks in advancea) Lac is not an international unit, so is not understood by everyone. This is an international forum so please use international units.
b) Please read the FAQ: {message:id=9360002} to learn how to format your question correctly for people to help you.
c) As your question relates to performance tuning, please also read the two threads linked to in the FAQ: {message:id=9360003} for an idea of what specific information you need to provide for people to help you tune your query. -
How can I get the sum of fields in group
example:
fieldA fieldB
2 30 group1
2 10
5 12 group2
5 14
5 9 group3
8 1
8 9
the values of fieldA in a group are the same.
each group i want to calculate fieldA only once: 258
how can i do this and display the sum at the first page of the report?Please re-post if this is still an issue to the Business Objects Integration Kits - SAP Forum or purchase a case and have a dedicated support engineer work with you directly
-
How to find the cumulative Sum
How to get the fastest result in 180 million records table to get the BTN(BillingTelephoneNbr) wise MonthlySalesCost.
select B.BTN,b.cost,sum(a.cost) as cum_sal
from Monthly_BTN a,Monthly_BTN b
where a.rowid <= b.rowid
group by b.rowid,b.BTN,b.cost.
Above query is taking up the too much time.
Option:-
a) partition the table
b) rebuild the index
c) alter the index
d) any other suggestion??
Let me know the best way.I don't understand why you need a self-join.
See the following example, with cumulative sum about deptno :
SCOTT@demo102> ed
Wrote file afiedt.buf
1 select empno, deptno, sal, sum(sal) over (partition by deptno order by empno)
2 from emp
3* order by deptno , empno
SCOTT@demo102> /
EMPNO DEPTNO SAL SUM(SAL)OVER(PARTITIONBYDEPTNOORDERBYEMPNO)
7782 10 24500 24500
7839 10 50000 74500
7934 10 13000 87500
7369 20 8000 8000
7566 20 29750 37750
7788 20 30000 67750
7876 20 11000 78750
7902 20 30000 108750
7499 30 16000 16000
7521 30 12500 28500
7654 30 12500 41000
7698 30 28500 69500
7844 30 15000 84500
7900 30 9500 94000
14 rows selected.
SCOTT@demo102> So, your query would be :
select BTN,cost,sum(cost) over (partition by BTN order by BTN,cost) as ***_sal
from Monthly_BTN
order by BTN,cost;Anyway, a query without where clause on a huge table (180 million records) seems to me like a little strange, are you sure that you will read all rows ?
Nicolas.
partition or not partition about BTN... like you want.
Message was edited by:
N. Gasparotto -
Hellow!
Sale person need to sale 238 pc of material X.
If we set price condition = 10,50 then order sum is 2.499,00
If we set price condition = 10,51 then order sum is 2.501,38
But customer ask as to set total order sum = 2.500
How could I manage it ?
Any condition to correct order sum ?
Andrey Garshin.hi,
why can't u use DIFF condition type and round off the decimals with prior approval from
your team lead.
Cheers,
Sailesh
Edited by: sistla sailesh on Mar 27, 2011 7:36 PM
Maybe you are looking for
-
Hello, I've been trying to save my created TDMS files as ZIP. Then I want to give password to my ZIP file. Could I do them programmatically? Yasemin Barutçu Electrical And Electronics Engineer
-
Detection of third party software
ok. My wife is the NETwork administator and I believe has either downloaded 3rd party software or is monitioring my internet usage. How can I tell? I can get into her Network Administrator account I just do not know hoew to find what I am looking for
-
When I click a sidebar bookmark, site opens in sidebar, not in Firefox page
Just reinstalled windows and Firefox
-
My company used Bugzilla in the past (I have never used it) to have the client mark and track changes to a site in developemnt via a testing server. They couldn't actually MAKE the changes themself (like a CMS tool) but it allowed the developers to s
-
Reading multiple result sets using executeQuery
Hi - We have a database Proc that returns multiple result sets as the out params. Following is the line that does the DB call. rows = DynamicSQL.executeQuery(sentence : query, implname : "Sql Server"); The 'rows' param above is able to get only the f