SUM not showing expected value in SQL - sql

I have a table as
ID TOTAL SUM(TOTAL)
1 62 62
1 53 53
2 62 62
2 47 47
I thought the SUM(TOTAL) should look like
ID TOTAL SUM(TOTAL)
1 62 115
1 53 115
2 62 109
2 47 109
This is the query I used
select ID, TOTAL, SUM(TOTAL)
from tablename
GROUP BY TOTAL, ID

You could do a windowed SUM instead:
Select ID, TOTAL, SUM(TOTAL) OVER(PARTITION BY ID)
From tablename
This will give you the results you expected. It will display the ID and TOTAL for each row, along with the SUM of the ID grouping.
A GROUP BY is not necessary for this type of summation.

You'll need to remove the TOTAL column from the group by, and therefore the select list. Because TOTAL is in your select list and group by it can't properly aggregate how you're expecting.
SELECT ID, SUM(TOTAL)
FROM tablename
GROUP BY ID
To get your exact output:
SELECT tablename.ID,
TOTAL,
TOTALSUM
FROM (SELECT ID,
SUM(TOTAL) AS TOTALSUM
FROM tablename
GROUP BY ID) AS t
INNER JOIN
tablename
ON tablename.ID = t.ID;

Related

Using two aggregate function - min and max on same query

Here is my product table's data -
product_id category discount
454 C-10 10
357 C-10 9
64 C-10 10
294 C-11 17
449 C-11 17
471 C-11 17
89 C-11 12
56 C-11 10
I want to get the max discount for every product category and if any category has multiple products having same discount, the product having the minimum
product_id should be selected.
Desired output -
product_id category discount
64 C-10 10
294 C-11 17
I tried below two query but not working -
select category,min(product_id),max(discount)
from Product
group by category
Your help is very much appreciated. Thanks!
Using ROW_NUMBER is helpful here:
WITH cte AS (
SELECT product_id, category, discount,
ROW_NUMBER() OVER (PARTITION BY category
ORDER BY discount DESC, product_id) rn
FROM Product
)
SELECT product_id, category, discount
FROM cte
WHERE rn = 1;
Or, we could even do this without using a subquery/CTE:
SELECT TOP 1 WITH TIES product_id, category, discount
FROM Product
ORDER BY
ROW_NUMBER() OVER (PARTITION BY category
ORDER BY discount DESC, product_id);
use row_number()
select * from
(
select *,row_number() over(partition by category order by discount desc, poroduct_id asc) rn
from tablename
)A where rn=1
OR
use correlated subquery
select * from tablename a where discount in
(select max(discount) from tablename b where a.category=b.category
having min(b.product_id)=a.product_id)
use outer apply
with cte as
(
select 454 as product_id, 'C-10' as category, 10 as discount union all
select 357,'C-10',9 union all
select 64,'C-10',10 union all
select 294,'C-11',17 union all
select 449,'C-11',17 union all
select 471,'C-11',17 union all
select 89,'C-11', 12 union all
select 56,'C-11', 10
) select distinct p1.category,a.product_id,a.discount
from cte p1
outer apply ( select top 1 p2.*
from cte p2 where p1.category=p2.category
order by discount desc, product_id asc
) a
output
category product_id discount
C-10 64 10
C-11 294 17
demo link

Fetch row with max occurrence in Oracle

I have a table like:
SALES
PROD_CODE SALE_ID
321 30
123 67
321 46
321 82
123 48
321 91
For the code:
SELECT PROD_CODE, COUNT(SALE_ID) AS TOTAL_SALES
FROM SALES
GROUP BY PROD_CODE
ORDER BY COUNT(SALE_ID) DESC;
The output is:
PROD_CODE TOTAL_SALES
321 4
123 2
But, when I am expecting only the prod_code with the maximum number of sales as the output,
like:
PROD_CODE
321
For the code:
SELECT PROD_CODE
FROM (SELECT MAX(COUNT(SALE_ID)) FROM SALES
GROUP BY SALE_ID);
The code isn't working!
In Oracle 12c+, you can do:
select s.prod_code
from sales s
order by count(*) desc
fetch first 1 row only;
In earlier versions, either
select s.*
from (select s.prod_code
from sales s
order by count(*) desc
) s
where rownum = 1;
Or:
select max(prod_code) over (dense_rank first order by cnt desc)
from (select s.prod_code, count(*) as cnt
from sales s
group by s.prod_code
) s
The first two versions fetch the entire row. You can limit it to one or more columns is that is all you want.
You could use stats_mode function to fetch row/column with maximum occurrence.
Here is detailed doc for this function https://docs.oracle.com/database/121/SQLRF/functions188.htm#SQLRF06320

Calculating the sum of running total colum

I am getting running total of particular column, but now I need to get the sum of running total column
id somedate somevalue runningtotal sumofrunning total
-- -------- --------- ------------ ------------------
45 01/Jan/09 3 3 138
23 08/Jan/09 5 8 138
12 02/Feb/09 0 8 138
77 14/Feb/09 7 15 138
39 20/Feb/09 34 49 138
33 02/Mar/09 6 55 138
Please try:
select
*,
SUM(RunningTotal) OVER() SumOfRunningTotal
from
YourTable
Store the result from your query in a temp table.
select ....
into # T
from ...
Calculate the sum value to a variable.
declare #sum bigint;
select sum(runningtotal)
from #T;
And finally do the query against the temp table.
select *, #sum as [sumofrunning total]
from #T
Another way would be to do a derived table of your existing query and use sum() over() in the main query.
select T.*, sum(T.runningtotal) over() as [sumofrunning total]
from (
-- your query goes here
select ...
from ...
)
Try this (UGLY and SLOW), but seems working,
WITH somecte (id, somedate, somevalue, runningtotal, somegroupe )
AS
(
SELECT
a.id,
a.somedate,
a.somevalue,
-- Here goes your running total logic
(SELECT SUM(b.somevalue)
FROM sometable b
WHERE b.somedate <= a.somedate) AS runningtotal,
1 as somegroupe
FROM sometable a
)
SELECT id, somedate, somevalue, runningtotal,
(SELECT SUM(runningtotal)
FROM somecte
GROUP BY somegroupe) AS sumofrunningtotal
FROM somecte
Check SQLFiddle

How to find distinct sum of a column in sql server?

I have a table like this structure:
lineID lineItemPrice
1 20
2 25
3 27
4 30
4 30
4 30
I want to get the sum of lineItemPrice where lineId is distinct.
I am not sure what should be sql query? Please help.
The output should be 102.
I cant quite tell if you are looking for this:
select
sum(lineItemPrice), lineID
from
table
group by lineID
Or this:
select
sum(lineItemPrice)
from
(select distinct lineID, lineItemPrice from table)
If you want the sum of the whole table:
select
sum(lineItemPrice)
from
table
The first would give results that would sum up all the lineItemPrice's for their respective lineID's
lineID lineItemPrice
1 20
2 25
3 27
4 90
The second would sum all these distinct records giving 102 as the answer
lineID lineItemPrice
1 20
2 25
3 27
4 30
The third:
lineItemPrice
162
Try this:
SELECT SUM(lineItemPrice) as TotalSum FROM
(SELECT lineItemPrice
FROM TableName
GROUP BY lineID,lineITemPrice) T
Result:
TOTALSUM
102
See result in SQL Fiddle.
Please try:
select
SUM(lineItemPrice) lineItemPrice
from(
select
distinct lineID, lineItemPrice
From tbl
)x
You can use below query if lineID lineITemPrice for a same value pair.
select
SUM(DISTINCT lineItemPrice) lineItemPrice
From tbl
This should work :
Select lineID, SUM(lineItemPrice) Total From YourTableName Group By lineID
Very Simple.
The GROUP BY statement is used in conjunction with the aggregate functions (we used SUM function here) to group the result-set by one or more columns.
Why Not this
SELECT * FROM
(
Select lineID, SUM(lineItemPrice) Over(Partition By lineID) Total
From TableName
) T
Group By lineID,Total
Fiddle Demo
Output:
lineID lineItemPrice
1 20
2 25
3 27
4 90

Sum function in SQL Server 2008

I have a table:
PropertyID Amount
--------------------------
1 40
1 20
1 10
2 10
2 90
I would like to achieve :
PropertyId Amount Total_Amount
---------------------------------------
1 40 70
1 20 70
1 10 70
2 10 100
2 90 100
using below query :
SELECT
PropertyID,
SUM(Amount),
SUM(TotalAmount)
FROM
yourTable
WHERE
EndDate IS NULL
GROUP BY
PropertyID
Output:
PropertyId Amount TotalAmount
-------------------------------------
1 70 70
2 100 100
Let me know how can I get my desired output ...
You can do this using window functions:
select PropertyID, Amount,
sum(Amount) over (partition by PropertyId) as TotalAmount
from yourtable;
The window function for sum() does the following. It calculates the sum of amount for groups of rows in the same group. The group is defined by the partition by clause, so rows with the same value of PropertyId are in the same group.
SELECT PropertyID,
Amount,
(select sum(yt.Amount)
from yourTable yt where yt.PropertyID==y.PropertyID and yt.EndDate IS NULL)
as TotalAmount
FROM yourTable y
WHERE y.EndDate IS NULL