Question

I'm creating an invoice sheet that groups each item into years, using Toad for Oracle to make my queries.

What I'm currently doing is using the same FROM and WHERE clauses as my views (as this data comes from multiple tables)

Select DISTINCT 
SUM(Credits * Credit_Price) as "Cost", to_char(START_DATE, 'YYYY') as "YEAR", 
PERSON_ID, ITEM_TYPE
[...]
WHERE
[...]
to_char(START_DATE, 'YYYY') = '2012'

When I look at the costs in the View I'd created I see entries with a cost of 0, 100, and 0 for the appropriate person,

but if I do the SUM/GROUP BY (grouping by item_type, person_id and to_char(START_DATE, 'YYYY')) I get a cost of 3860700 for the same person!

Any ideas on how to fix this so I get 100 instead of 3860700?

EDIT: So basically I want a quantity*cost but to sum it so I get the total for that item type (instead of having multiple rows for the same item).

Was it helpful?

Solution

In SQL SELECT distinct sum() will not sum distinct values, so you need to first select the distinct values and then sum them up:

Select  
SUM(Credits * Credit_Price) as "Cost", to_char(START_DATE, 'YYYY') as "YEAR", 
PERSON_ID, ITEM_TYPE
[...]
 from (select DISTINCT Credits , Credit_Price, START_DATE,PERSON_ID, ITEM_TYPE
[...])
WHERE
[...]
to_char(START_DATE, 'YYYY') = '2012'

or put the distinct inside the sum like this:

Select  
SUM(DISTINCT Credits * Credit_Price) as "Cost", to_char(START_DATE, 'YYYY') as "YEAR", 
PERSON_ID, ITEM_TYPE
[...]
WHERE
[...]
to_char(START_DATE, 'YYYY') = '2012'

Note that the 2 options aren't equel, do you want to sum the distinct Credits , Credit_Price or the distinct Credits * Credit_Price ?

See sqlfiddle example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top