Calculate the sum of group in a table and joining on other table sql - sql

i have two tables in sql.
table_team
t_id team_name
1 ABC
2 XYZ
3 PQR
i have another table_player
p_id t_id player_name payment
10 1 Sam 1000
20 1 jon 500
30 2 will 680
40 1 bob 700
50 3 rob 890
i want to get the team's total payment from these two tables.
i'e sum of payemnt of each player in a particular team, and for all teams.
i thought of trying
select t_id,team_name,sum(b.payment) as total_payment from table_team a
left join table_player b on a.t_id = b.t_id

Join to a subquery which computes the total payment for each team:
SELECT t1.t_id, t1.team_name, t2.total_payment
FROM table_team t1
INNER JOIN
(
SELECT t_id, SUM(payment) AS total_payment
FROM table_player
GROUP BY t_id
) t2
ON t1.t_id = t2.t_id
-- WHERE t1.team_name IN ('ABC', 'XYZ')

select t_id,team_name,sum(b.payment) as total_payment
from table_team a
left join table_player b on a.t_id = b.t_id
group by t_id,team_name

select t_id,team_name,sum(isnull(b.payment,0)) as total_payment from table_team a
left join table_player b on a.t_id = b.t_id
group by t_id, team_name
Just add a group by and it should work

Related

How to Sum previos rows summatory to find a balance in SQL Server

I'm working on a service that needs to calculate how much a customer owes, according to a total invoice value and the partial payments that the customer has made.
So, in a tableA I have a row with the invoice total value:
[dbo].[TableA]
ID CustomerId InvoiceVal
1 12 1000
2 11 2000
3 10 5000
4 14 15000
5 12 100
6 16 8000
7 18 3200
In a TableB I have the record of each customer's partial payments they have made to each invoice:
[dbo].[TableB]
ID InvoiceId Payment
1 1 150
2 3 50
3 1 120
4 1 100
5 5 90
6 4 7500
So, as you can see, the customer 12 has an invoice for $1000 and has made 3 payment that sum $370
I need to be able to se the partial total owed in each row, this is the expected result:
No. InoviceId CustomerId Payment Owed
1 1 12 150 850
2 1 12 120 730
3 1 12 100 630
So far, this is my code:
DECLARE #invid int = '1'
DECLARE #invoicetotal numeric(18,2)
SET #invoicetotal =
(
SELECT
[dbo].[TableA].[InvoiceVal]
FROM [dbo].[TableA]
WHERE
([dbo].[TableA].[ID] = #invid)
)
SELECT
*,
SUM(#invoicetotal - [dbo].[TableB].[Payment]) OVER(ORDER BY [dbo].[TableB].[ID] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS [Owed]
FROM [dbo].[TableB]
WHERE
([dbo].[TableB].[InvoiceId] = #invid)
But this is what I get:
ID InvoiceId Payment Owed
1 1 150.00 NULL
3 1 120.00 850.00
4 1 100.00 1730.00
I need to sum the previous payment on each row.
Thanks!
Something like this would help
SELECT
ROW_NUMBER() OVER (ORDER BY TableB.ID ASC) NO,
CustomerId,
Payment,
InvoiceVal - SUM(Payment) OVER (PARTITION BY TableA.ID ORDER BY TableB.Id ASC) Owed
FROM TableA
INNER JOIN TableB
ON TableA.Id = TableB.InvoiceId
WHERE
CustomerId = 12
Working Fiddle
Your query will depend on what you are trying to make as your final output.
If you want just ONE CustomerID, go with:
SELECT a.ID AS InvoiceID, a.CustomerID, a.InvoiceVal AS StartInvoice
, b.ID AS bid, b.Payment
, a.InvoiceVal - ISNULL(SUM(b.Payment) OVER (PARTITION BY a.ID ORDER BY b.id),0) AS owed
FROM TableA a
LEFT OUTER JOIN TableB b ON a.ID = b.InvoiceID
WHERE a.CustomerID = 12
And if that CustomerID doesn't have any payments, you want to use a LEFT JOIN so that you don't eliminate an amount owed.
SELECT a.ID AS aid, a.CustomerID, a.InvoiceVal AS StartInvoice
, b.ID AS bid, b.Payment
, a.InvoiceVal - ISNULL(SUM(b.Payment) OVER (PARTITION BY a.ID ORDER BY b.id),0) AS owed
FROM TableA a
LEFT OUTER JOIN TableB b ON a.ID = b.InvoiceID
WHERE a.CustomerID = 11
I also added an ISNULL() around Payment to keep from nulling out your owed amount. It could also be added to the InvoiceVal to account for a CustomerID who hasn't been invoiced yet, if that was needed (or possible from other tables).
IF you want to get ALL CustomerIDs, you'll have to account for that in your partition.
SELECT s1.CustomerID, aid AS InvoiceID, s1.bid, s1.Payment
, (s1.StartInvoice - s1.runningPayment) AS Owed
FROM (
SELECT a.ID AS aid, a.CustomerID, a.InvoiceVal AS StartInvoice
, b.ID AS bid, b.Payment
, ISNULL(SUM(b.Payment) OVER (PARTITION BY a.CustomerID, a.ID ORDER BY b.id),0) AS runningPayment
FROM TableA a
LEFT OUTER JOIN TableB b ON a.ID = b.InvoiceID
) s1
ORDER BY s1.CustomerID, s1.aid, s1.bid
Fiddle demonstrates overpayment or paying total balance for 0 owed.

SQL Server 2005 MAX, SUM AND GROUP BY

I am using SQL Server 2005 and I have a problem with my SQL query. Basically, I want to get the total amount of all transactions of customers, grouped by company, based on the latest dates from all customer transactions.
Sample data:
Customer_Id Date Amount COMPANY
-------------------------------------------------
1 3/3/2014 9021 COMPANY X
2 3/3/2014 12000 COMPANY Y
2 3/15/2014 10000 COMPANY Y
2 3/30/2014 8000 COMPANY Y
4 3/13/2014 10000 COMPANY Z
5 3/14/2014 1400 COMPANY X
1 3/16/2014 2500 COMPANY X
7 3/14/2014 110 COMPANY Y
3 3/17/2014 1500 COMPANY Z
2 3/19/2014 2044 COMPANY Y
3 3/09/2014 9400 COMPANY Z
3 3/11/2014 8950 COMPANY Z
2 3/31/2014 3455 COMPANY Y
3 3/15/2014 950 COMPANY Z
6 3/15/2014 5543 COMPANY X
What I want to accomplish is like this:
COMPANY TOTAL
COMPANY X 9443 --> sum from customer_id 1 (2500, as of 3/16/2014) and customer_id 6 (5542, 3/15/2014) and customer_id 5 (1400 as of 3/14/2014)
COMPANY Y 3455 --> sum from customer_id 2 (3455, as of 3/31/2014)
COMPANY Z 10950 --> sum from customer_id 4 (1000, as of 3/13/2014) and customer_id 3 (950, as of 3/15/2014)
Below are some SQL queries I've tried which doesn't work on my goal:
SELECT TOP (1) WITH TIES
Date, Company, SUM(Amount) AS total
FROM
tbl_Table
GROUP BY
Date, Company
ORDER BY
Date DESC
SELECT
t1.Date, t1.Company, SUM(t1.Amount) AS total
FROM
tbl_Table AS t1
INNER JOIN
(SELECT
MAX(Date) AS date, Company
FROM
tbl_Table
GROUP BY
Company) AS t2 ON t1.Date = t2.Date AND t1.Company = t2.Company
GROUP BY
t1.Date, t1.Company
WITH latest AS
(SELECT
Company, MAX(Date) AS maxdate
FROM
tbl_Table
GROUP BY
Company
)
SELECT
a.Date, a.Company, SUM(a.Amount) AS total
FROM
tbl_Table AS a
INNER JOIN
latest AS b ON a.Company = b.Company AND a.Date = b.maxdate
GROUP BY
a.Date, a.Company
Your results are still not correct by data you give.
SQLFIDDLEExample
Query:
SELECT t1.Company,
SUM(t1.Amount) Total
FROM Table1 t1
LEFT JOIN Table1 t2
ON t1.COMPANY = t2.COMPANY
AND t1.Customer_Id = t2.Customer_Id
AND t1.Date < t2.Date
WHERE t2.Customer_Id is null
GROUP BY t1.Company
Result:
| COMPANY | TOTAL |
|-----------|-------|
| COMPANY X | 9443 |
| COMPANY Y | 3565 |
| COMPANY Z | 11500 |
Try This
WITH cte AS (
SELECT Amount,Company,
ROW_NUMBER() OVER (PARTITION BY Customer_Id ORDER BY CAST([Date] AS DATETIME) desc )
AS dateRowRank
)
SELECT Company,SUM(Amount)
FROM cte
WHERE dateRowRank=1
GROUP BY Company

sql join query for multiple tables

I have following tables structure,
cust_info:
cust_id cust_name
1 nikhil
2 sam
bill_info:
bill_id cust_id bill_amount
7 1 10000
8 1 15000
9 2 6000
10 2 4000
paid_info:
paid_id cust_id paid_amount
11 1 5000
12 1 5000
13 2 5000
14 2 5000
now my output should display sum of bill made by customer and total amount paid by that customer and balance amount
output
cust_id total_bill total_paid balance
1 25000 10000 15000
2 10000 10000 0
where,
for example,
for cust_id = 2,
total_bill= 10000 + 15000
total_paid = 5000 + 5000
balance = total_bill - total_paid
what is convenient way to do this in sql? any sample query?
here's what i've already tried
SELECT distinct c.cust_id
, sum(b.bill_amount) as total_bill
, SUM(p.paid_amt) AS totalpaid,sum(b.bill_amount) - SUM(p.paid_amt) AS balance
FROM cust_info c
INNER JOIN bill_info b ON c.cust_id = b.cust_id
INNER JOIN paid_info p ON p.cust_id= b.cust_id group by p.cust_id;
SELECT
cust_info.cust_id,
cust_name,
bill_amount,
paid_amount,
bill_amount - paid_amount AS balance
FROM cust_info
INNER JOIN (
SELECT cust_id, SUM(bill_amount) bill_amount
FROM bill_info
GROUP BY cust_id
) bill_info ON bill_info.cust_id = cust_info.cust_id
INNER JOIN (
SELECT cust_id, SUM(paid_amount) paid_amount
FROM paid_info
GROUP BY cust_id
) paid_info ON paid_info.cust_id = cust_info.cust_id
demo
SELECT c.cust_id,
SUM(b.total_bill),
SUM(p.total_paid),
SUM(c.total_bill) - SUM(p.total_paid)
FROM
cust_info c
LEFT JOIN bill_info b ON (c.cust_id = b.cust_id)
LEFT JOIN paid_info p ON (c.cust_id = p.party_id)
GROUP
BY cust_info.cust_id
SELECT DISTINCT cust_info.cust_id,
sum(bill_amount) AS 'total_bill' ,
sum(paid_amount) AS 'total paid' ,
(SUM(bill_amount) - sum(paid_amount)) AS balance
FROM cust_info
INNER JOIN bill_info ON cust_info.cust_id = bill_info.cust_id
INNER JOIN paid_info ON cust_info.cust_id = paid_info.cust_id
GROUP BY cust_info.cust_id

How to get this result with and only with SQL?

The question is:
Two tables (t1, t2)
Table t1:
SELLER | NON_SELLER
A B
A C
A D
B A
B C
B D
C A
C B
C D
D A
D B
D C
Table t2:
SELLER | COUPON | BAL
A 9 100
B 9 200
C 9 300
D 9 400
A 9.5 100
B 9.5 20
A 10 80
Using SELECT Statement to get this result:
SELLER| COUPON | SUM(BAL)
A 9 900
B 9 800
C 9 700
D 9 600
A 9.5 20
B 9.5 100
C 9.5 120
D 9.5 120
A 10 0 # !!!
B 10 80
C 10 80
D 10 80
For seller A SUM(BAL) means sum( B.BAL,C.BAL,D.BAL), for B, SUM(BAL)=SUM(A.BAL,C.BAL,D.BAL)...
Please find a way with good performance and don't use temporary table.
My solution:
Running this query will get the result but without the row "A 10 0":
select t1.seller, t2.coupon, sum(bal)
from t1, t2
where t1.non_seller = t2.seller
group by t1.seller, t2.coupon
order by t2.coupon
Please help ~~~~~~
If I understand you correctly, you're looking for data on all sellers and all coupons. So let's start with a cross join that generates a list of coupons and sellers:
select sellers.seller
, coupons.coupon
from (
select distinct seller
from Table2
) as sellers
cross join
(
select distinct coupon
from Table2
) as coupons
For each seller-coupon combination, you're looking for the sum they can buy from other sellers. This can be accomplished by a left join:
select sellers.seller
, coupons.coupon
, case when sum(t2.bal) is null then 0 else sum(t2.bal) end
from (
select distinct seller
from Table2
) as sellers
cross join
(
select distinct coupon
from Table2
) as coupons
left join
Table2 t2
on t2.seller <> sellers.seller
and t2.coupon = coupons.coupon
group by
sellers.seller
, coupons.coupon
The only function of the case statement is to replace a null sum with a 0.
The output matches the one in your answer. Note that this solution doesn't use Table1: the list of other sellers is produced by the t2.seller <> sellers.seller condition in the left join.
I get another way to this:
select t1.seller, t2.coupon, sum(bal)
from t1, t2
where t1.non_seller = t2.seller
group by t1.seller, t2.coupon
union
(select seller,coupon,0 from t2 group by coupon having count(seller) == 1);
And I don't know if it is better or worst than compare with #Andomar :
select sellers.seller
, coupons.coupon
, case when sum(t2.bal) is null then 0 else sum(t2.bal) end
from (
select distinct seller
from Table2
) as sellers
cross join
(
select distinct coupon
from Table2
) as coupons
left join
Table2 t2
on t2.seller <> sellers.seller
and t2.coupon = coupons.coupon
group by
sellers.seller
, coupons.coupon

SQL Query to sum fields from different tables

I'm a humble programmer that hates SQL ... :) Please help me with this query.
I have 4 tables, for example:
Table A:
Id Total
1 100
2 200
3 500
Table B
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
Table C
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
Table D
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
I need to make a SELECT that shows the Id, the Total and the SUM of the Amount fields of tables B, C and D like this
Id Total AmountB AmountC AmountD
1 100 43 43 43
2 200 55 55 55
3 500 65 65 65
I've tried with a inner join of the three tables by the Id and doing a sum of the amount fields but results are not rigth. Here is the wrong query:
SELECT dbo.A.Id, dbo.A.Total, SUM(dbo.B.Amount) AS Expr1, SUM(dbo.C.Amount) AS Expr2, SUM(dbo.D.Amount) AS Expr3
FROM dbo.A INNER JOIN
dbo.B ON dbo.A.Id = dbo.B.ExtId INNER JOIN
dbo.C ON dbo.A.Id = dbo.C.ExtId INNER JOIN
dbo.D ON dbo.A.Id = dbo.D.ExtId
GROUP BY dbo.A.Id, dbo.A.Total
Thanks in advance, its just that I hate SQL (or that SQL hates me).
EDIT: I had a typo. This query is not giving the right results. Extended the example.
Or you can take advantage of using SubQueries:
select A.ID, A.Total, b.SB as AmountB, c.SC as AmountC, d.SD as AmountD
from A
inner join (select ExtID, sum(Amount) as SB from B group by ExtID) b on A.ID = b.ExtID
inner join (select ExtID, sum(Amount) as SC from C group by ExtID) c on c.ExtID = A.ID
inner join (select ExtID, sum(Amount) as SD from D group by ExtID) d on d.ExtID = A.ID
From your description, this query should give you an error as you are using the non-existent column dbo.A.Amount in your group by. Changing this to dbo.A.Total might be what you need.
If you need all the amounts together, then try this query:
select A.Id, A.Total, sum(B.Amount + C.Amount + D.Amount) AS Total_Amount
from A
inner join B on A.Id = B.ExtId
inner join C on A.Id = C.ExtId
inner join D on A.Id = D.ExtId
group by A.Id, A.Total;
This one also works well
SELECT (SELECT SUM(Amount) FROM TableA) AS AmountA,
(SELECT SUM(Amount) FROM TableB) AS AmountB,
(SELECT SUM(Amount) FROM TableC) AS AmountC,
(SELECT SUM(Amount) FROM TableD) AS AmountD
This might help other users.
SELECT Total=(Select Sum(Amount) from table a)+(Select Sum(Amount) from table b)+(Select Sum(Amount) from table c)
Try this code
SELECT Total=isnull((Select Sum(Isnull(Amount,0)) from table a),0)+isnull((Select Sum(isnull(Amount,0)) from table b),0)+isnull((Select Sum(isnull(Amount,0)) from table c),0)