Calculate total of particular column in sql query - sql

I want to calculate total of particular column
For ex my table must looks like this
Customername Payment id RunningTotal
a 500 5 5
b 500 10 10
c 300 10 7
------ -----------
1300 22
I am getting the table but now I want to calculate the total mentioned at the end for the column Payment and RunningTotal.

If you are getting the above result from table t1, then you can add your sum at the end by using an Union statement. Something like this
select Customername, Payment, id, RunningTotal
from t1
union all
select null,sum(payment),null,sum(runningtotal or any total)
from t1
This will add total payments and the other total at the end of the result.

SELECT Sum(Payment) AS Total FROM tablename;
Output: Total = 1300

select sum(Payment) as SumPayment, sum(RunningTotal) as SumRunningTotal
from yourTable

Without GROUPBY clause use OVER()
Example:
select Customername, sum(Payment) OVER () AS TotalPayment, id, sum(RunningTotal) over()
as RunningTotal
from t1

if you want to sum all rows, its as simple as:
select sum(payment) payment_sum, sum(runningtotal) runningtotal_sum
from customers;

select Customername ,id ,sum(Payment) as Payment , sum(RunningTotal) as RunningTotal from Table group by Customername ,id with rollup

Related

How to take the MAX of a column and subtract it from all values in that same column in SQL Server?

Here's the table:
PersonID
amount
1
10
1
10
2
30
3
40
I'm trying to take the max of "amount", which is 40 and subtract it from all values from the same column so that it looks like this
PersonID
amount
1
20 (40-(10+10)
2
10 (40-30)
3
0 (40-50)
SELECT
PersonID, MAX(Price) - Price
FROM
(SELECT
PersonID, SUM(amount) AS Price
FROM sales
GROUP BY PersonID) Alias1
GROUP BY
PersonID
The problem is that I get an error when running this query:
Column 'Alias1.Price' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
If your version of SQL support analytic functions, then use MAX() that way:
SELECT PersonID, MAX(SUM(amount)) OVER () - SUM(amount) AS amount
FROM sales
GROUP BY PersonID;
Demo
Here is an approach which does not use analytic functions:
WITH cte AS (
SELECT PersonID, SUM(amount) AS amount
FROM sales
GROUP BY PersonID
)
SELECT PersonID, (SELECT MAX(amount) FROM cte) - amount AS amount
FROM cte;

Calculating the product of two columns from each row and generate sum result total using Microsoft SQL

I'm looking for something nice and sweet that will enable me to take the product of two columns per row and then take each of these products and sum them together for a final total.
The solution must be compatible with MS SQL 2008/2012.
Example of table.
|---------------------|------------------|
| Qty | Price |
|---------------------|------------------|
| 12 | 34.25 |
|---------------------|------------------|
| 44 | 11.05 |
|---------------------|------------------|
The result of this table should be calculated like this:
Row 1:
12 * 34.25 = 411
Row 2:
44 * 11.05 = 486.20
FINAL CALCULATED RESULT:
897.20
Thank you,
First multiply each quantity with their price.
SELECT
T.*,
TotalByRow = Quantity * Price
FROM
YourTable AS T
Then do a sum of all the results.
SELECT
Total = SUM(Quantity * Price)
FROM
YourTable AS T
If you need the result by product (or any grouped column) you can add a GROUP BY clause (in the previous example, when using an aggregate function such as SUM() without a GROUP BY then the whole table is considered a group).
SELECT
T.ProductID,
Total = SUM(Quantity * Price)
FROM
YourTable AS T
GROUP BY
T.ProductID
Use GROUPING SETS to get the grand total.
Query
select [Qty], [Price], sum([Qty] * [Price]) as [Total]
from [your_table_name]
group by grouping sets(([Qty], [Price]), ());
i always calculate the entire total in my client, but you can do it in sql too like this :
declare #table table (qty int, price decimal(16,2))
insert into #table(qty, price) values (12, 34.25), (44, 11.05)
select qty,
price,
sum(qty * price) as total
from #table
group by grouping sets((qty, price), ())
The result is this
qty price total
--- ----- -----
12 34,25 411
44 11,05 486,2
897,2
More info on grouping sets here https://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx
Try this.
SELECT TOP(1) TOTAL_AMOUNT
FROM (
SELECT QTY
, PRICE
, QTY*PRICE 'AMOUNT'
, SUM(QTY*PRICE) OVER( ORDER BY QTY ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING ) 'TOTAL_AMOUNT'
FROM PRODUCT ) AS GET_SUM
ORDER BY GET_SUM.TOTAL_AMOUNT DESC
--SECOND SOLUTION:
select SUM(qty*price) 'Amount'from product

Query 2 sum in 1 table

table a
column id : a a b b
column total : 1 2 1 3
how can i show? in one table without use compute
a 3 7
b 4 7
Do group by to sum each id's total. Do a sub-select to count total:
select id,
sum(total) as total,
(select sum(total) from a) as totalall
from a
group by id
Using window functions with a distinct, it can be simply expressed like this:
select distinct id,
sum(Total) over(partition by id) total,
Sum(Total) over () total_all
from mytable
SQL Fiddle
One way is to use OUTER APPLY. You could also set a variable to the sum of the table and call that variable.
select a.id, sum(a.total) as total, b.Grand as GrandTotal
from tablea a
outer apply
(select sum(total) as Grand from tablea) b
group by a.id

How to filter max value records in SQL query

I want to get all records except max value records. Could you pls suggest query for that.
For eg,(Im taking AVG field to filter)
SNO Name AVG
1 AAA 85
2 BBB 90
3 CCC 75
The query needs to return only 1st and 3rd records.
Use the below query:
select * from tab where avg<(select max(avg) from tab);
You could use a ranking function like DENSE_RANK:
WITH CTE AS(
SELECT SNO, Name, AVG,
RN = DENSE_RANK() OVER (ORDER BY AVG DESC)
FROM dbo.TableName
)
SELECT * FROM CTE WHERE RN > 1
(if you are using SQL-Server >= 2005)
Demo
select * from Sample where avg not in (select max(avg) from sample);
I think this should do
Try this
SELECT SNO, Name, AVG
FROM TableName
WHERE AVG NOT IN (SELECT MAX(AVG)
FROM TableName )

SUM of grouped COUNT in SQL Query

I have a table with 2 fields:
ID Name
-- -------
1 Alpha
2 Beta
3 Beta
4 Beta
5 Charlie
6 Charlie
I want to group them by name, with 'count', and a row 'SUM'
Name Count
------- -----
Alpha 1
Beta 3
Charlie 2
SUM 6
How would I write a query to add SUM row below the table?
SELECT name, COUNT(name) AS count
FROM table
GROUP BY name
UNION ALL
SELECT 'SUM' name, COUNT(name)
FROM table
OUTPUT:
name count
-------------------------------------------------- -----------
alpha 1
beta 3
Charlie 2
SUM 6
SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
FROM Table GROUP BY name
Without specifying which rdbms you are using
Have a look at this demo
SQL Fiddle DEMO
SELECT Name, COUNT(1) as Cnt
FROM Table1
GROUP BY Name
UNION ALL
SELECT 'SUM' Name, COUNT(1)
FROM Table1
That said, I would recomend that the total be added by your presentation layer, and not by the database.
This is a bit more of a SQL SERVER Version using Summarizing Data Using ROLLUP
SQL Fiddle DEMO
SELECT CASE WHEN (GROUPING(NAME) = 1) THEN 'SUM'
ELSE ISNULL(NAME, 'UNKNOWN')
END Name,
COUNT(1) as Cnt
FROM Table1
GROUP BY NAME
WITH ROLLUP
Try this:
SELECT ISNULL(Name,'SUM'), count(*) as Count
FROM table_name
Group By Name
WITH ROLLUP
all of the solution here are great but not necessarily can be implemented for old mysql servers (at least at my case). so you can use sub-queries (i think it is less complicated).
select sum(t1.cnt) from
(SELECT column, COUNT(column) as cnt
FROM
table
GROUP BY
column
HAVING
COUNT(column) > 1) as t1 ;
Please run as below :
Select sum(count)
from (select Name,
count(Name) as Count
from YourTable
group by Name); -- 6
The way I interpreted this question is needing the subtotal value of each group of answers. Subtotaling turns out to be very easy, using PARTITION:
SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]
This is what my full SQL call looks like:
SELECT MAX(GroupName) [name], MAX(AUX2)[type],
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
FROM [MyView]
WHERE Active=1 AND Type='APP' AND Completed=1
AND [Date] BETWEEN '01/01/2014' AND GETDATE()
AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
GROUP BY AUX2, GroupId
The data returned from this looks like:
name type count total
Training Group 2 Cancelation 1 52
Training Group 2 Completed 41 52
Training Group 2 No Show 6 52
Training Group 2 Rescheduled 4 52
Training Group 3 NULL 4 10535
Training Group 3 Cancelation 857 10535
Training Group 3 Completed 7923 10535
Training Group 3 No Show 292 10535
Training Group 3 Rescheduled 1459 10535
Training Group 4 Cancelation 2 27
Training Group 4 Completed 24 27
Training Group 4 Rescheduled 1 27
You can use union to joining rows.
select Name, count(*) as Count from yourTable group by Name
union all
select "SUM" as Name, count(*) as Count from yourTable
For Sql server you can try this one.
SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE
with cttmp
as
(
select Col_Name, count(*) as ctn from tab_name group by Col_Name having count(Col_Name)>1
)
select sum(ctn) from c
You can use ROLLUP
select nvl(name, 'SUM'), count(*)
from table
group by rollup(name)
Use it as
select Name, count(Name) as Count from YourTable
group by Name
union
Select 'SUM' , COUNT(Name) from YourTable
I am using SQL server and the following should work for you:
select cast(name as varchar(16)) as 'Name', count(name) as 'Count'
from Table1
group by Name
union all
select 'Sum:', count(name)
from Table1
I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries
SYNTAX:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;
Example:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;
You can try group by on name and count the ids in that group.
SELECT name, count(id) as COUNT FROM table group by name
After the query, run below to get the total row count
select ##ROWCOUNT
select sum(s) from
(select count(Col_name) as s from Tab_name group by Col_name having count(*)>1)c