mySQL - SUM of column - mysql

I have 2 tables
table 1
id product
1 P1
2 P2
table 2
id amount product_t1
1 100 P1
2 200 P1
3 300 P2
4 400 P1
5 500 P2
I want my output to be:
product totalAmount(sum of amount)
P1 700
P2 800
EDIT: Here is my query so far
SELECT T1.product, SUM(T2.amount)
FROM table1 T1
INNER JOIN table2 T2
ON T1.product = T2.product_t1
Thanks!

you should use group by
SELECT T1.product, SUM(T2.amount)
FROM table1 T1
INNER JOIN table2 T2
ON T1.product = T2.product_t1
GROUP BY product

Since you're not using foreign keys you don't even need the table 1 for the desired result.
SELECT
product_t1 AS product,
SUM(amount) AS totalAmount
FROM table2
GROUP BY product_t1
What you're missing is the GROUP BY statement in order to get a separate row for each individual product

SELECT T1.product, SUM(T2.amount)
FROM table1 T1
INNER JOIN table2 T2
ON T1.product = T2.product_t1
GROUP BY product T1.product
Use the GROUP BY tag . Group by helps to group your result via value of product

Try to play with GROUP BY and AS
SELECT product_t1 as product, SUM(amount) AS totalAmount FROM table2
GROUP BY product
https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html
OR add to your code group by
SELECT T1.product, SUM(T2.amount)
FROM table1 T1
INNER JOIN table2 T2 ONT1.product = T2.product_t1
Gruop by T1.product

Related

Select from 1 table sum from 2 but 1 table has a AND condition

Thanks for assisting with the previous query (SQL Query that selects a column in table 1 and uses that to select sum in table 2) of SUM from 2 tables, I now have a additional Condition for 1 of the tables. I would like to add WHERE Group1 = 1 AND IN/OUT = 'OUT'
I have 3 tables,
Names ,Groups
Names ,Payments
Names ,Payments and IN/OUT
I want to only SUM the OUT Payments in Table 3, I am getting total payments only So FAR is have:
SELECT t1.name1, SUM(t2.sale2),SUM(t3.sale3)
FROM table1 t1 JOIN table2 t2 ON t1.name1 = t2.name2
JOIN table3 t3 ON t1.name1 = t3.name3
WHERE group1 = 1
GROUP BY t1.name1
i would also like to add a zero if there is no data to sum instead of removing the whole record, Currently if a name has no payments in Table 3 but has payments in table 2 it deletes the record.
Please check the query below =>
To Get OutPayment group by Name
SELECT t1.Names,SUM(t3.Payments) As OutPayment
FROM TABLE3 as t3
INNER JOIN TABLE1 as t1 ON t1.Names = t3.Names
INNER JOIN TABLE2 as t2 ON t1.Names = t2.Names
WHERE t1.GroupID = 1 AND t3.INOROUT=2 --INOROUT =2 is OUT and 1 is IN
GROUP BY t1.Names;
To Get TotalOutPayment
SELECT SUM(t3.Payments) As TotalOutPayment
FROM TABLE3 as t3
INNER JOIN TABLE1 as t1 ON t1.Names = t3.Names
INNER JOIN TABLE2 as t2 ON t1.Names = t2.Names
WHERE t1.GroupID = 1 AND t3.INOROUT=2; --INOROUT =2 is OUT and 1 is IN
Note: Code is in DBFiddle too Check the Demo Query Link

How do I find the users biggest donation? without aggregate functions

For example given
table1
userId donation
1 50
1 150
1 340
1 20
2 85
2 15
I want
userId donation
1 340
2 85
I thought about cross joining them and see which was bigger but don't know what to do after this
SELECT * FROM
table1 as T1 cross join table1 as T2
WHERE
T1.userId = T2.userId
and
T1.donation > T2.donation
I think you are looking for something like this:
select *
from table1 T1
where not exists (
select 1
from table1 T2
where T2.userId=T1.userId and T2.donation > T1.donation
)
or the equivalent join:
select *
from table1 T1
left join table1 T2 on T2.userId=T1.userId and T2.donation > T1.donation
where T2.userId is null
If there are two rows with the same donation, both of them will be selected. If you don't want that, also compare primary key columns or some other unique keys:
T2.userId=T1.userId and (T2.donation,T2.primarykeycol1,T2.primarykeycol2) > (T1.donation,T1.primarykeycol1,T1.primarykeycol2)
You can use a self join and then compare the highest donation with the records of secondary table but same user.
SELECT T1.userId, T1.donation
FROM table1 T1
LEFT JOIN table1 T2 ON T1.userId = T2.userId AND T1.donation < T2.donation
WHERE T2.id IS NULL;
MySQL 8
WITH s1 AS (
SELECT userId,
donation,
RANK() OVER (PARTITION BY userId ORDER BY donation DESC) AS `Rank`
FROM table1
)
SELECT s1.userId, s1.donation
FROM s1
WHERE s1.`Rank` = 1;

Select count with join in SQL query

How can I check how many products added by a,b,c,d respectively by using a query?
table1
admin_id admin_name
3 a
4 b
5 c
6 d
table2
admin_id products
3 pDeal
3 pSeal
4 pAeal
5 pZeal
6 pXeal
3 pHeal
6 pPeal
You need a simple JOIN and a COUNT query:
SELECT table1.admin_name, COUNT(*) as cnt
FROM
table1 INNER JOIN table2
ON table1.admin_id = table2.admin_id
GROUP BY
table1.admin_name
Try this...
SELECT a.admin_name, COUNT(b.products) as 'CountOfProducts'
FROM table1 a INNER JOIN table2 b ON a.admin_id = b.admin_id
GROUP BY a.admin_name
Use this
SELECT adm.admin_name,COUNT(pdr.products) as ProductCnt
FROM table1 AS adm
JOIN table2 AS pdr
ON adm.admin_id = pdr.admin_id
GROUP BY adm.admin_id;
SELECT t1.admin_name, COUNT(t2.products)
FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.admin_id = t2.admin_id
WHERE 1
GROUP BY t2.admin_id
The LEFT JOIN will ensure the cases when table2 doesn't have any record for some admin of table 1.
You can use an inner-select like this:
SELECT
table1.admin_name,
(SELECT COUNT(*)
FROM table2
WHERE table1.admin_id = table2.admin_id) As cnt
FROM
table1;

mysql sum on JOINED table with different group condition

I have a query as the following
SELECT
sum(price),
count(id),
sum case(when spec='bath' then price else 0 END) as bath_money
FROM
table1
LEFT JOIN table2 ON table1.id = table2.fkt1
LEFT JOIN table3 ON table2.id = table3.fkt2
WHERE 1
group by sale;
Now my problem is that table 3 has 2 rows for each row in Table 2. Table 2 is the one I actually use to add up sales and to sum price but since I need to left join for Table 3 everything is added twice.
Would there be a way of adding up prices of table 2 ignoring all double lines generated by joining Table 3? Otherwise I'd just write another query, but I'd like to know whether I can do a sum ignoring a specific join??
Does this work :
SELECT
sum(price),
count(id),
sum(case when spec='bath' then price else 0 END) as bath_money
FROM table1 t1
LEFT JOIN table2 ON table1.id = table2.fkt1
LEFT JOIN (select * from table3 GROUP BY fkt2) table3a ON table2.id = table3a.fkt2
group by sale;
You can try something like
SELECT
sum(t1.price),
count(t1.id),
sum (case when t2.spec='bath' then t2.price else 0 END) as bath_money
FROM
table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.fkt1
LEFT JOIN table3 t3 ON t2.id = t3.fkt2
group by t1.sale

Sum of two columns from two tables - MySQL

I have three tables
t1
CustId Name
1 XYZ
2 PQR
t2
CustId Income
1 100
1 200
2 50
2 100
t3
CustId Expense
1 50
1 70
2 30
2 40
I need to run a query where I get the below result
CustId Total Income Total Expense
1 300 120
2 150 70
I have tried the normal SUM and Group By but the result is very different from the expected...
The Query I attempted was
SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1
LEFT JOIN t2 ON t1.custId = t2.CustId
LEFT JOIN t3 ON t1.CustId = t3.CustId
GROUP BY t1.CustId
Any help you would appreciated....
Try below query.
SELECT t1.CustID, IFNULL(tbl1.Income,0) AS 'TotalIncome', IFNULL(tbl2.Expenses,0) AS 'TotalExpenses'
FROM t1
LEFT JOIN (SELECT t2.CustID,SUM(Income) AS 'Income' FROM t2 GROUP BY t2.CustID) tbl1
ON t1.CustID = tbl1.CustID
LEFT JOIN (SELECT t3.CustID,SUM(Expenses) AS 'Expenses' FROM t3 GROUP BY t3.CustID) tbl2
ON t1.CustID = tbl2.CustID;
SQL Fiddle: http://sqlfiddle.com/#!9/ad05d/8
Try doing inner join all three tables and then grouping the result by customer id like:
SELECT t1.custId, SUM(t2.Income), SUM(t3.expense)
FROM t1 INNER JOIN t2
ON t1.custId = t2.custId
INNER JOIN t3
ON t2.custId = t3.custId
GROUP BY t1.custId
You can use the following query to achieve what you want
SELECT t1.custid, ti.Income, te.expense FROM t1 LEFT JOIN (select t2.custId, sum(t2.Income) as income from t2 group by t2.custId) as ti ON t1.custId = ti.CustId LEFT JOIN (select t3.custId, sum(t3.Expense) as expense from t3 group by t3.custId) as te ON t1.CustId = te.CustId
As far as why your previous query did not worked. I can give the following explanation.
In SQL when ever you do a join, the way database internally makes a cartesian product of all the entries and depending on the where clause the data is returned. So when you did
SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1 LEFT JOIN t2 ON t1.custId = t2.CustId
You got 4 rows, where customerId is repeated in the rows, now when you join with t3 table by applying the equal condition on customerId, database would be able to match customerID in two records and hence you get 8 rows. That is why your query was not working