Need Query to do a Sum functionality
Hi,
I have a table named Employee. The columns are Name varhcar2(10) and Salary Number(10,0)
The Entries in the field are
Name Salary
Bob 25000
Alen 30000
Rose 15000
Ann 20000
I want to find the salary of Alen and Sum of Salary of other members in a single query.
The output should be Salary of Alen - 30000 and Total Salary of others - 60000
Please help me
Thanks,
Bisin
Hi Bisin,
Do you mean like this?
SQL> create table mytable (name,salary)
2 as
3 select 'Bob', 25000 from dual union all
4 select 'Alen', 30000 from dual union all
5 select 'Rose', 15000 from dual union all
6 select 'Ann', 20000 from dual
7 /
Table created.
SQL> select case name
2 when 'Alen' then 'Salary of Alen'
3 else 'Total Salary of others'
4 end
5 , sum(salary)
6 from mytable
7 group by case name
8 when 'Alen' then 'Salary of Alen'
9 else 'Total Salary of others'
10 end
11 /
CASENAMEWHEN'ALEN'THEN SUM(SALARY)
Salary of Alen 30000
Total Salary of others 60000
2 rows selected.Regards,
Rob.
Similar Messages
-
Why do we need query rewrite enabled for a function-based index?
Oracle 9i
========
I have searched a few sites but could not find any content on it. The question is why do we need to implement query rewrite enabled when we are trying out a function-based index?
Thanks in advance.You don't, that's a legacy requirement from the early days of function based indexes in Oracle 8i. Here's a quick example running under 9.2.0.6
drop table t1;
create table t1 as
select
from
all_objects
where
rownum <= 30000
create or replace function pl_func(i_vc varchar2)
return varchar2
deterministic
as
begin
return soundex(i_vc);
end;
-- set the worst case scenario
alter session set query_rewrite_enabled = false;
alter session set query_rewrite_integrity = enforced;
create index t1_i1 on t1(pl_func(object_name));
execute dbms_stats.gather_table_stats(user, 't1')
set autotrace traceonly explain
select
object_name
from t1
where pl_func(object_name) = 'T513'
set autotrace offResults (after set feedback off)
SQL> @temp
Execution Plan
Plan hash value: 1429545322
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 27 | 675 | 10 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T1 | 27 | 675 | 10 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | T1_I1 | 27 | | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("TEST_USER"."PL_FUNC"("OBJECT_NAME")='T513')
SQL> spool offRegards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk -
Issues using SUM Function in query
I have pasted two queries Query1 (calculating counts for total_ships and ships_released) and Query2 (calculating the two same counts and then calculating SUM for total_shipments and I am having problem in this)
Query 1:
select b.loc , b.week, b.vvalue2, b.Total_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
from (
SELECT l.loc , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date , count(distinct s.ship_id ) as ships_rel_total
FROM ship s, loct l,
ship_num sr1, ship_num sr, ship_stat ss, ship_stat ss1
WHERE ......
Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
) A,
( SELECT distinct l.loc , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
FROM ship s, loct l,
ship_num sr1, ship_num sr, ship_stat ss, ship_stat ss1
WHERE ......
Group by c.loc , c.week , c.vvalue2 ) B
where a.loc (+) = b.loc
and a.vvalue2 (+) = b.vvalue2
order by b.loc, b.week , b.vvalue2,a.up_date; Query 1 Output:
*OUTPUT*
LOC WEEK VALUE2 TOTAL_SHIPS DATEE TOtAL_SHIPS_RELEASED
AA 111 BB 12 10-05-12 2
AA 111 BB 12 11-05-12 4
AA 111 CC 2 14-05-12 1Then I added sum function for total_ships and its not giving me result what I need :(
Query 2:
select b.loc , b.week, b.vvalue2, b.sum_ships, nvl(a.up_date,'None') as datee , nvl( a.ships_rel_total,0) as Total_released
from (
SELECT l.loc , sr1.vvalue1 as Week, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD') as up_date , count(distinct s.ship_id ) as ships_rel_total
FROM ship s, loct l,
ship_num sr1, ship_num sr, ship_stat ss, ship_stat ss1
WHERE ......
Group by l.loc , sr1.vvalue1, sr.vvalue2 , to_char(ss.udate, 'YYYY-MM-DD')
) A,
( Select c.loc, c.week , c.vvalue2 , sum(c.total_ships) sum_ships
from
( SELECT distinct l.loc , sr1.vvalue1 as Week, sr.vvalue2 , count(s.ship_id ) as Total_Ships
FROM ship s, loct l,
ship_num sr1, ship_num sr, ship_stat ss, ship_stat ss1
WHERE ......
Group by l.loc , sr1.vvalue1 , sr.vvalue2 ) C
Group by c.loc , c.week , c.vvalue2 ) B
where a.loc (+) = b.loc
and a.vvalue2 (+) = b.vvalue2
order by b.loc, b.week , b.vvalue2,a.up_date; my query is giving me this :(
Query 2 Output:
LOC WEEK VALUE2 *SUM_SHIPS* DATEE TOtAL_SHIPS_RELEASED
AA 111 BB 26 10-05-12 2
AA 111 BB 26 11-05-12 4
AA 111 CC 26 14-05-12 1
But I need a result like this:
LOC WEEK VALUE2 SUM_SHIPS DATEE TOtAL_SHIPS_RELEASED
AA 111 BB 14 10-05-12 2
AA 111 BB 14 11-05-12 4
AA 111 CC 14 14-05-12 1Hi,
It sounds like you have a Fan Trap , where a one-to-many relationship is causing some items to be counted many times.
The usual solution is to compute the aggregates before doing the one-to-many join. Analytic functions may make this simpler.
Sorry, I can't show you exactly how to do it without the exact data.
Post CREATE TABLE and INSERT statements for all tables involved, and also post the results you want from that data (if different from what you've already posted).
Explain, using specific examples, how you get those results from that data.
Simplify the problem as much as possible. If the problem only concerns the total_ships column, then only post the data needed to compute total_ships. This includes all the columns involved in the joins and GROUP BY clauses.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002} -
Need complex query with joins and AGGREGATE functions.
Hello Everyone ;
Good Morning to all ;
I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
I want to make complex join with AGGREGATE FUNCTION.
my table details
SQL> select from tab;*
TNAME TABTYPE CLUSTERID
DEPT TABLE
PAYROLL TABLE
EMP TABLE
SQL> desc emp
Name
EID
ENAME
EDOB
EGENDER
EQUAL
EGRADUATION
EDESIGNATION
ELEVEL
EDOMAIN_ID
EMOB_NO
SQL> desc dept
Name
EID
DNAME
DMANAGER
DCONTACT_NO
DPROJ_NAME
SQL> desc payroll
Name
EID
PF_NO
SAL_ACC_NO
SALARY
BONUS
I want to make complex query with joins and AGGREGATE functions.
Dept names are : IT , ITES , Accounts , Mgmt , Hr
GRADUATIONS are : Engineering , Arts , Accounts , business_applications
I want to select records who are working in IT and ITES and graduation should be "Engineering"
salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
Please help me to make a such complex query with joins ..
Thanks in advance ..
Edited by: 969352 on May 25, 2013 11:34 AM969352 wrote:
why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
My Goal is :
1. When executing my own query i need to check expalin plan.please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
Best Wishes on your quest for performance improvements. -
Please help me at this query (sum function)
hi every one
if I have column and the datatype is varchar2 and in this column has data like
number,number mix varchar2,and character
i want use sum function to summarize then number only but i want to ignore any number with char
this example
12
23
1q2
wer
34rt
the result=35
thanks in advanceNot sure what you need here.
However here is a sample of what's possible:
SQL> WITH test_data AS
2 (
3 SELECT '12' AS DAT FROM DUAL UNION ALL
4 SELECT '23' AS DAT FROM DUAL UNION ALL
5 SELECT '1q2' AS DAT FROM DUAL UNION ALL
6 SELECT '34rt' AS DAT FROM DUAL
7 )
8 SELECT SUM(DAT)
9 FROM test_data
10 WHERE NOT REGEXP_LIKE(DAT,'[^[:digit:]]')
11 /
SUM(DAT)
35 -
Error when using SUM function in Excel template
I am trying to use the XDO_METADATA to create a sum of a column from my XML data and I am getting the following error in the Template Viewer:
[111412_104246459][][PROCEDURE] Log Level is changed to PROCEDURE
[111412_104246553][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
Time: 0.125 sec.
FO Formatting failed.
<Line 317, Column 116>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
@Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//G_CR_MST_D/V_CR_MO_IDD)"/>
when I use:
XDO_?SUM_V_CR_MO_IDD1? <?sum(.//G_CR_MST_D/V_CR_MO_IDD)?>
or
[111412_104048508][][PROCEDURE] Log Level is changed to PROCEDURE
[111412_104048554][oracle.xdo.common.xml.XSLTWrapper][ERROR] XSL error:
Time: 0.078 sec.
FO Formatting failed.
<Line 317, Column 105>: XML-23029: (Error) FORG0001: invalid value for cast/constructor
@Line 317 ==> <Cell Index="2" Style="R7C3" Field="XDO_?SUM_V_CR_MO_IDD1?"><xsl:value-of select="sum(.//V_CR_MO_IDD)"/>
when I use:
XDO_?SUM_V_CR_MO_IDD1? <?sum(.//V_CR_MO_IDD)?>
I believe the XSL to be correct because when I change it to a count it works and when I go into BI Publisher 11g and create the query in the data model and then create a summary from it, the summary is created.
Can anyone help?I went back to basics and created reports (via EXCEL templates) like I was asking based on good old EMP and DEPT and I found exactly the same problems I was mentioning. I looked at the templates provided but they were not calculating totals, like me they were selecting them and then just displaying them on the page.
Anyway, I have narrowed it down to the fact that when you do aggregates like sum(.//SAL) this works if you have a salary for every value. I did an outer join with DEPT so I did have empty rows and why I still experienced the problems.
Basically XSL does not like adding (including using the sum function) values that effectively have nulls in them which is why I get the cast/constructor errors because it is trying to turn a NaN value to a number and does not (or cannot) do it.
You need to either have a value in every row of your column (maybe possible by selecting nvl in your query) and make sure that you check the "create empty nodes" checkbox in the data model of BI Publisher.,
the other solution is an xsl solution where you would have to make sure that you only added non null values and for that you would have to investigate xsl blogs.
It is, by the way, why my count worked because it is just counting that the record exists it does not care what the element content is or isn't.
Closing thread. -
How can I use SUM function to calculate # of employees in the comp.&deptnt?
I've got two tables: employee & department. I am trying to calculate total employees by department and total employees by the entire company. I know I need to use SUM function, but I only can calculate total employees by department & by company separately. I need to get this output:
DEPT_NAME DEPT_TOTAL_SALARY COMPANY_TOTAL_SALARY
RESEARCH 10875 29025
SALES 9400 29025
ACCOUNTING 8750 29025
This is my code:
SELECT department_name, SUM(salary) as total_salary
FROM employee, department
WHERE employee.department_id = department.department_id
GROUP BY department_name;
SELECT SUM(salary)
FROM employee;
Can somebody help please?
Thank you in advance.Edited by: user13675672 on Jan 30, 2011 2:29 PM
Edited by: user13675672 on Jan 30, 2011 2:31 PMHi, Peter
Peter Gjelstrup wrote:
... There might be a smarter way, with no re-select.You're right, as usual.
SELECT d.dname
, SUM (e.sal) AS dept_tot_sal
, SUM (SUM (e.sal)) OVER () AS comp_tot_sal
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
GROUP BY d.dname
;Analytic functions are computed after aggregate functions, so an aggregate function can be nested inside an analytic function.
Another way (without a sub-query, at least) would be SELECT DISTINCT, with only analytic functions.
SELECT DISTINCT
d.dname
, SUM (e.sal) OVER (PARTITION BY d.dname) AS dept_tot_sal
, SUM (e.sal) OVER () AS comp_tot_sal
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
; -
Post Author: deejayw
CA Forum: Formula
Hi,I am trying to create a formula which works like the Sum function but will give me the difference between two amounts.Scenario:Each record has a username, invoice date and invoice amount. My data set contains two months of data which means for each username, i have two invoice amounts and invoice dates. I know the Sum function will add values together but how can i get the difference between two values, namely last months invoice amount and this months invoice amount (order is important).Do i need to use an array or is my brain so fried that i'm missing something simple?ThanksPost Author: satyanat
CA Forum: Formula
Hi,
Instead of having the two months invoice details in a single query you can write it as two queries, one to pull the current month invoice date,amount and the other one to pull the previous month Invoice. you can link both queries on User name through visual link.
Now you can easily find the difference between the two invoice amounts.
ex: {previousmonth.invoiceamt} - {currentmonth.invoiceamt}
Try this option.
Regards,
Natarajan -
Need some help with the Table Function Operator
I'm on OWB 10gR2 for Sun/Solaris 10 going against some 10gR2 DB's...
I've been searching up and down trying to figure out how to make OWB use a Table Function (TF) which will JOIN with another table; allowing a column of the joined table to be a parameter in to the TF. I can't seem to get it to work. I'm able to get this to work in regular SQL, though. Here's the setup:
-- Source Table:
DROP TABLE "ZZZ_ROOM_MASTER_EX";
CREATE TABLE "ZZZ_ROOM_MASTER_EX"
( "ID" NUMBER(8,0),
"ROOM_NUMBER" VARCHAR2(200),
"FEATURES" VARCHAR2(4000)
-- Example Data:
Insert into ZZZ_ROOM_MASTER_EX (ID,ROOM_NUMBER,FEATURES) values (1,'Room 1',null);
Insert into ZZZ_ROOM_MASTER_EX (ID,ROOM_NUMBER,FEATURES) values (2,'Room 2',null);
Insert into ZZZ_ROOM_MASTER_EX (ID,ROOM_NUMBER,FEATURES) values (3,'Room 3','1,1;2,3;');
Insert into ZZZ_ROOM_MASTER_EX (ID,ROOM_NUMBER,FEATURES) values (4,'Room 4','5,2;5,4;');
Insert into ZZZ_ROOM_MASTER_EX (ID,ROOM_NUMBER,FEATURES) values (5,'Room 5',' ');
-- Destination Table:
DROP TABLE "ZZZ_ROOM_FEATURES_EX";
CREATE TABLE "ZZZ_ROOM_FEATURES_EX"
( "ROOM_NUMBER" VARCHAR2(200),
"FEATUREID" NUMBER(8,0),
"QUANTITY" NUMBER(8,0)
-- Types for output table:
CREATE OR REPLACE TYPE FK_Row_EX AS OBJECT
ID NUMBER(8,0),
QUANTITY NUMBER(8,0)
CREATE OR REPLACE TYPE FK_Table_EX AS TABLE OF FK_Row_EX;
-- Package Dec:
CREATE OR REPLACE
PACKAGE ZZZ_SANDBOX_EX IS
FUNCTION UNFK(inputString VARCHAR2) RETURN FK_Table_EX;
END ZZZ_SANDBOX_EX;
-- Package Body:
CREATE OR REPLACE
PACKAGE BODY ZZZ_SANDBOX_EX IS
FUNCTION UNFK(inputString VARCHAR2) RETURN FK_Table_EX
AS
RETURN_VALUE FK_Table_EX := FK_Table_EX();
i NUMBER(8,0) := 0;
BEGIN
-- TODO: Put some real code in here that will actually read the
-- input string, parse it out, and put data in to RETURN_VALUE
WHILE(i < 3) LOOP
RETURN_VALUE.EXTEND;
RETURN_VALUE(RETURN_VALUE.LAST) := FK_Row_EX(4, 5);
i := i + 1;
END LOOP;
RETURN RETURN_VALUE;
END UNFK;
END ZZZ_SANDBOX_EX;
I've got a source system built by lazy DBA's and app developers who decided to store foreign keys for many-to-many relationships as delimited structures in driving tables. I need to build a generic table function to parse this data and return it as an actual table. In my example code, I don't actually have the parsing part written yet (I need to see how many different formats the source system uses first) so I just threw in some stub code to generate a few rows of 4's and 5's to return.
I can get the data from my source table to my destination table using the following SQL statement:
-- from source table joined with table function
INSERT INTO ZZZ_ROOM_FEATURES_EX(
ROOM_NUMBER,
FEATUREID,
QUANTITY)
SELECT
ZZZ_ROOM_MASTER_EX.ROOM_NUMBER,
UNFK.ID,
UNFK.QUANTITY
FROM
ZZZ_ROOM_MASTER_EX,
TABLE(ZZZ_SANDBOX_EX.UNFK(ZZZ_ROOM_MASTER_EX.FEATURES)) UNFK
Now, the big question is--how do I do this from OWB? I've tried several different variations of my function and settings in OWB to see if I can build a single SELECT statement which joins a regular table with a table function--but none of them seem to work, I end up getting SQL generated that won't compile because it doesn't see the source table right:
INSERT
/*+ APPEND PARALLEL("ZZZ_ROOM_FEATURES_EX") */
INTO
"ZZZ_ROOM_FEATURES_EX"
("ROOM_NUMBER",
"FEATUREID",
"QUANTITY")
(SELECT
"ZZZ_ROOM_MASTER_EX"."ROOM_NUMBER" "ROOM_NUMBER",
"INGRP2"."ID" "ID_1",
"INGRP2"."QUANTITY" "QUANTITY"
FROM
(SELECT
"UNFK"."ID" "ID",
"UNFK"."QUANTITY" "QUANTITY"
FROM
TABLE ( "ZZZ_SANDBOX_EX"."UNFK2" ("ZZZ_ROOM_MASTER_EX"."FEATURES")) "UNFK") "INGRP2",
"ZZZ_ROOM_MASTER_EX" "ZZZ_ROOM_MASTER_EX"
As you can see, it's trying to create a sub-query in the FROM clause--causing it to just ask for "ZZZ_ROOM_MASTER_EX"."FEATURES" as an input--which isn't available because it's outside of the sub-query!
Is this some kind of bug with the code generator or am I doing something seriously wrong here? Any help will be greatly appreciated!Hello Everybody!
Thank you for all your response!
I had changes this work area into Internal table and changed the select query. PLease let me know if this causes any performance issues?
I had created a Z table with the following fields :
ZADS :
MANDT
VKORG
ABGRU.
I had written a select query as below :
I had removed the select single and insted of using the Structure it_rej, I had changed it into Internal table
select vkorg abgru from ZADS into it_rej.
Earlier :
IT_REJ is a Work area:
DATA : BEGIN OF IT_REJ,
VKORG TYPE VBAK-VKORG,
ABGRU TYPE VBAP-ABGRU,
END OF IT_REJ.
Now :
DATA : BEGIN OF IT_REJ occurs 0,
VKORG TYPE VBAK-VKORG,
ABGRU TYPE VBAP-ABGRU,
END OF IT_REJ.
I guess this will fix the issue correct?
PLease suggest!
Regards,
Developer. -
How can I sum up raws? the Sum function seems to work only on columns. Right now I have to create a separate formula for each raw
Hi dah,
"Thanks, but can I do one formula for all present and future raws? as raws are being added, I have to do the sum function again and again"
You do need a separate formula for each group of values to be summed.
If the values are in columns, you need a copy of the formula for each column.
If the values are in rows, you need a copy of the formula for for each row.
If you set up your formulas as SGIII did in his example (shown below), where every non-header row has the same formula, Numbers will automtically add the formula to new rows as you add them.
"Same formula" in this context means exactly the same as all the formulas above, with one exception: the row reference in each formula is incremented (by Numbers) to match the row containing the formula.
Here the formula looks like this in the three rows shown.
B2: =SUM(2)
B3: =SUM(3)
B4: =SUM(4)
That pattern will continue as rows are added to the table.
Also, because the row token (2) references all of the non-header cells in row 2, the formula will automatically include new columns as they are added to the table.
Regards,
Barry -
COUNT() and SUM() function it not working in XDO file.
Hi ,
I am getting one error. Count and sum function not working proper.
For example :
Department 10 have 3 employee and total salary is 8750. But my report returning total employee 1 and total salary 5000
10
Ename Sal
KING 5000
CLARK 2450
MILLER 1300
==================
total employee : 1
total salary : 5000
Kindly help me solve this problem.
<dataTemplate name="TEXT">
<properties>
<property value="upper" name="xml_tag_case" />
</properties>
<lexicals>
</lexicals>
<dataQuery>
<sqlstatement name="Q_TEMP">
<![CDATA[SELECT DEPTNO,DNAME,LOC FROM DEPT]]>
</sqlstatement>
<sqlstatement name="Q_TEMP1">
<![CDATA[SELECT ENAME,HIREDATE,SAL FROM EMP WHERE DEPTNO = :DEPTNO]]>
</sqlstatement>
</dataQuery>
<datastructure>
<GROUP name="G_1" source="Q_TEMP">
<element value="DEPTNO" name="DEPTNO" />
<element value="DNAME" name="DNAME" />
<element value="LOC" name="LOC" />
<GROUP name="G_2" source="Q_TEMP1">
<element value="ENAME" name="ENAME" />
<element value="SAL" name="SAL" />
<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />
<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>
</GROUP>
</GROUP>
</datastructure>
</dataTemplate>
Thanks
YudhiPlease have the data structure as below:
<datastructure>
<GROUP name="G_1" source="Q_TEMP">
<element value="DEPTNO" name="DEPTNO" />
<element value="DNAME" name="DNAME" />
<element value="LOC" name="LOC" />
<GROUP name="G_2" source="Q_TEMP1">
<element value="ENAME" name="ENAME" />
<element value="SAL" name="SAL" />
*</GROUP>*
*<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
*<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
*</GROUP>*
</datastructure>
Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there. -
Using Sum Function in Oracle(on 24 th)
Hi all i wrote the following query.
SELECT RESPONSER_ID,SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,COUNT(DISTINCT QUESTION_ID) AS QCOUNT FROM TQDB_LEARNER_RESPONSE WHERE RESPONSER_ID=328
GROUP BY RESPONSER_ID
I am getting the following error.
ORA-00937: not a single-group group function
Any body Pls help me.why use sum(sum()
SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,
SELECT
RESPONSER_ID,
SUM(DISTINCT WORK_SPACE) AS SCORE,
COUNT(DISTINCT QUESTION_ID) AS QCOUNT
FROM
TQDB_LEARNER_RESPONSE
WHERE
RESPONSER_ID=328
GROUP BY
RESPONSER_ID Regards
Singh -
Hi everyone,
I have a problem with SUM function in SQL query on Oracle 11g database. Maybe you will be able to help me.
Problem:
I want to shows summary costs for shipments separately for each service provider and for each month they did the shipments.
Data is stored in SHIPMENT AND SHIPMENT_COST table as shown below. The problem is that summary function I use sums base costs (marked as B in SHIPMENT_COST table) for each accessorial cost (marked as A in SHIPMENT_COST table). In example for shipment 10005031 we have 4 accessorial costs so it shows 6120 in BASE_COST column. I tried to use distinct in summary but then we have a problem with shipment id 201307133713_0383 which has 3 base costs equal to 221.54 so with distinct it will show 221.54 instead of 221.54x3.
SHIPMENT table:
START_TIME SHIPMENT_GID SERVPROV_GID
2013-06-25 10005031 T222176
2013-06-15 201307133713_0383 T76180
SHIPMENT_COST table:
SHIPMENT_GID COST COST_TYPE
10005031 1530 B
10005031 30.6 A
10005031 120 A
10005031 400 A
10005031 100 A
201307133713_0383 221.54 B
201307133713_0383 221.54 B
201307133713_0383 221.54 B
RESULT table:
SHIPMENT_START_DATE
SERVPROV
BASE_COST
CLAIM_COST
06/2013
T76180
664.62
null
06/2013
T222176
6120
650.6
Query:
SELECT DISTINCT TO_CHAR(SH.START_TIME,'MM/YYYY') AS SHIPMENT_START_DATE,
SH.SERVPROV_GID AS SERVPROV,
SUM(SHCOST.COST) AS BASE_COST,
SUM(SHCOST_CLAIM.COST) AS CLAIM_COST
FROM SHIPMENT SH,
SHIPMENT SHC
LEFT OUTER JOIN SHIPMENT_COST SHCOST ON (SHC.SHIPMENT_GID = SHCOST.SHIPMENT_GID AND SHCOST.COST_TYPE = 'B'),
SHIPMENT SHC_CLAIM
LEFT OUTER JOIN SHIPMENT_COST SHCOST_CLAIM ON (SHC_CLAIM.SHIPMENT_GID = SHCOST_CLAIM.SHIPMENT_GID AND SHCOST_CLAIM.COST_TYPE = 'A')
WHERE 1=1
AND SHC.SHIPMENT_GID = SH.SHIPMENT_GID
AND SHC_CLAIM.SHIPMENT_GID = SH.SHIPMENT_GID
AND SH.SHIPMENT_GID IN ('10005031','201307133713_0383')
GROUP BY TO_CHAR(SH.START_TIME,'MM/YYYY'),
SH.SERVPROV_GID
Best Regards,
Łukaszwith SHIPMENT (START_TIME,SHIPMENT_GID,SERVPROV_GID) as
select to_date('2013-06-25','yyyy-mm-dd'),'10005031','T222176' from dual union all
select to_date('2013-06-15','yyyy-mm-dd'),'201307133713_0383','T76180' from dual
SHIPMENT_COST(SHIPMENT_GID,COST,COST_TYPE)
as
select '10005031','1530','B' from dual union all
select '10005031','30.6','A' from dual union all
select '10005031','120','A' from dual union all
select '10005031','400','A' from dual union all
select '10005031','100','A' from dual union all
select '201307133713_0383','221.54','B' from dual union all
select '201307133713_0383','221.54','B' from dual union all
select '201307133713_0383','221.54','B' from dual
select *
from (select to_char(t.START_TIME, 'mm/yyyy'),
t.SERVPROV_GID,
c.COST,
c.COST_TYPE
from SHIPMENT t
join SHIPMENT_COST c
on t.SHIPMENT_GID = c.SHIPMENT_GID)
pivot(sum(COST) for COST_TYPE in('A' CLAIM_COST,'B' BASE_COST))
TO_CHAR(T.START_TIME,'MM/YYYY'
SERVPROV_GID
CLAIM_COST
BASE_COST
06/2013
T76180
664.62
06/2013
T222176
650.6
1530
Ramin Hashimzade -
Need of exception handler in calling function, isn't that weird???
Hi,
I have written a function as follows
public String fetchName(String query) throws Exception
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
return (rs.getString(1));
I've handled the for exceptions here using "throws Exception". Inspite of that when i call it from other function and in that funtion no exception need to be handled, compiler gives errror.
Following is the calling funtion
public String checksubAction(String action)
String retValue=" ";
String query="";
query = "select Title from dbo.Folder where Folder_Id="+folderId;
retValue = dataBaseObj.fetchName(query);
but when i write it in try-catch block, no errror is given.
Why is it that inspite of handling exception(s) in the called function, we need to handle them in calling functions.No you have not handled the exception. Your code say "fetchName" does NOT handle exceptions of type "Exception", the calling method should be aware of this, and handle that type of exception.
The Java Tutorial: Essential Java Classes: Handling Errors Using Exceptions
(Please when declaring a method can throw exceptions, be specific, i.e. throw SQLException in this case) -
Help with SUM function ??
Hi,
I am trying to build a SUM function into the following SELECT statement;
SELECT emp_code "EmployeeCode", trn_date "TransactionDate", project "ProjectCode",
phase_code "PhaseCode", task_code "TaskCode", reg_hrs "RegularHoursAmt", rate_reg "RegularHoursRate", ot_hrs "OvertimeHoursAmt", rate_ot "OvertimeHoursRate"
Currently when i do the extract to xls I manually compile the "RegularHoursAmt" and "RegularHoursRate" manually and it's quite a task. I'm sure it can be completed in teh SELECT but I'm not clear on how and it's been quite some time since my last foray into SQL. Any assistance appreciated.
I need to sum "RegularHoursAmt" and "RegularHoursRate"
per "EmployeeCode"
by "TransactionDate"
with unique combo of "ProjectCode", "PhaseCode", "TaskCode"
Cheers, PeterHi, Peter,
PJS5 wrote:
Thanks Frank for the quick response. Ok, here goes;
The TABLES already exist and I am only pulling the data for the columns in my SELECT statement so no CREATE of INSERT as such.Post CREATE TABLE and INSERT statements so that the people who want to help you can re-create the problem and test their ideas.
The data is in Oracle 10g 10.1.0.2.0Perfect!
So you want totals that represent the entire day for a given employee.
Yes, but rows are by the unique combo per employee of "ProjectCode", "PhaseCode", "TaskCode"So a row of output will represent a distinct combination of employee, day, ProjectCode, PhaseCode and TaskCode, and that one output row may correspond to more than one row of input; is that right?
eg Tom works on 4 unique "ProjectCode/PhaseCode/TaskCode" efforts on "TransactionDate"What does "effort" mean here? If I could look at some actaul data (or actual fake data; don't post anything like real credit card numbers) and the results you want from that data, perhaps it would be clear.
One of those unique "ProjectCode/PhaseCode/TaskCode" efforts however has 3 timesheet entries as he has added unique Descriptions of what his efforts were aimed at achieving.
We are not extracting the Descriptions and thereby want to SUM those 3 timesheet entries into one row.
Do you also want a total for each employee, over all days? No thanks
Do you want a grand total for all employees and all days? No thanks
Do you want the totals on the same output rows as your current reuslts? That would be handy
If so, use the analytic SUM function. I'm not familiar with this
Do you want separate rows for the the totals? That could helpPost the exact results you want from a small set of given data. It's fine to describe the results, as you did above, but describe them in addition to (not instead of) actually showing them.
Does that make my questions easier to follow?It looks good, but without some sample data and the results you want from that data, I can't say for sure.
Please post CREATE TABLE and INSERT statements (relevant columns only) for a little sample data, so that I (and the others who want to help you) can see exactly what your tables are like, and actually try our solutions. Simplify as much as possible. For example, if the data is actually coming from a multi-table join, but you already know how to join all the tables perfectly, then pretend all the data is in one table, and post CREATE TABLE and INSERT statements for that one table that looks sort of like your current result set. Post just enough data to show what you want to do. Based on what you've said so far, I'm guessing that 10 to 20 rows of raw data, resulting in 3 to 7 rows of output could give a nice example.
Also, post the exact results you want from the sample data you post. Explain, with specific examples, how you get those results from that data.
If parts of your desired output are optional (that is, if some parts "would be handy" or "could help") then post a couple of different sets of results from the same data, and explain, something like this:
"What I'd really love to get for results is" ...
but, if that makes things really complicated or inefficient, I don't absolutely need ... or ...,
so I'd settle for these results: ..."
I know it's a lot of work to post all this information, but it's really necessary. If I could help you without making you do all this, then I would. Unfortunately, I really don't have a good idea of where you're coming from or where you want to go.
Edited by: Frank Kulash on Oct 19, 2010 8:01 PM
Maybe you are looking for
-
IPhone messages show numbers and not contact names
My iPhone in messenger is showing phone numbers and not contacts. My contacts are OK, was working Ok just stopped today. Not sure why?
-
View settings for ATV in iTunes
Hi, Has any noticed that in itunes you are unable to change the view settings of the stuff synced to your ATV? If you select ATV in the device list and then click on any of the categories (movies/music etc) iTunes won't let you change ANY views, ever
-
Invalid serial number adobe 9 standard
I have checked the serial number with Adobe Support I am currently running windows 8. I have tried installing it on 2 machines without any success. After I put in the serial number it said's invalid serial number XXXXXX Invalid Serial number. This is
-
Beats audio controls not working
Using my beats headphones this morning with my MacBook Air and iTunes. Everything is up to date. Although today now the audio controls on the cord won't work. Normally I can pause iTunes or control the volume. I do this multiple times a day but n
-
Question About the iHome.
I'm just wondering about the iHome. I haven't bought one yet but i'm looking into it. I'm just wondering when you dock it, does it always start charging? I'm worried because they say there is about 400 cycles of charging and if I charge it too much t