I would like to left join three tables in one result and when I'm doing it like that: http://sqlfiddle.com/#!9/546c24/2 my result is wrong as you see.
I want COUNT(Test2.id) to be 2 and SUM(Test3.positive) to be 3 and not both 6.
That's my problem. I hope it's understandable.
You are getting a Cartesian product for each test1.id. You need to aggregate before the JOINs:
SELECT t1.id,Test1.name, t2.cnt_2,
t3.sum_pos, t3.sum_neg
FROM Test1 t1 LEFT JOIN
(SELECT ID_Test1, COUNT(*) as cnt_2
FROM Test2
GROUP BY ID_Test1
) t2
ON t1.id = t2.ID_Test1 LEFT JOIN
(SELECT ID_Test1, SUM(positive) as sum_pos, SUM(negative) as sum_neg
FROM Test3
GROUP BY ID_Test1
) t3
ON t1.id = t3.ID_Test1
GROUP BY t1.id;
Here is the SQL Fiddle.
Related
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
First of all, I'm an amateur on SQL. Here it is the example. From this three tables I would like to know how is called the teacher who makes more money with the classes:
Table1:
LessonName TeacherID
Maths 3
Biology 2
Biology 1
Geology 1
Table2:
Lesson PricePerClass
Maths 200
Biology 100
Geology 150
Table3:
IDTeacher TeacherName
1 Mike
2 John
3 Lauren
My main problem is that I don't know how to deal with the repeated values from the first table when I'm doing the triple join.
So far "I've made" this:
select IDTeacher, PricePerClass
from Table1 as T1
inner join Table2 as T2 on t1.LessonName = t2.Lesson
inner join Table3 as T3 on t1.TeacherId = t3.idTeacher
...
And I don't know how to keep going. I will have to group the t1.LessonName but every time I try to do it I get syntax errors. As you can see I'm pretty lost.
EDIT: My expected result would be something like:
IDTeacher TotalRevenue
1 250
Thanks a lot.
join the tables, group by teacher to aggregate and get the top row after you sort by the total descending:
select t3.IDTeacher, sum(t2.PricePerClass) TotalRevenue
from Table3 t3
inner join Table1 as t1 on t1.TeacherId = t3.IDTeacher
inner join Table2 as t2 on t2.Lesson = t1.LessonName
group by t3.IDTeacher
order by TotalRevenue desc limit 1
Note that this query does not return ties, if any.
SELECT t3.IDTeacher, t3.TeacherName, sum(t2.PricePerClass) from table1 t1
inner join table3 t3 on t1.TeacherID = t3.IDTeacher
inner join table2 t2 on t1.Lessonname = t2.Lesson
group by t3.TeacherName
order by sum(t2.PricePerClass) desc limit 1;
I have one query that returns count and some columns from two tables and another query that returns count and a column from two tables.
I want to combine this two queries that results in single row per id.
i have tried this:
select
(select a.column_1 as ID,a.column_2,COUNT(b.column_2) as Cnt1
from
table_1 a left outer join table_2 b on a.ID=b.ID
group by
a.column_1 as ID,a.column_2
)
where EXISTS
(select a.column_1 as ID,COUNT(c.column_2) as Cnt2
from
table_1 a left outer join table_3 c on a.ID=c.ID
group by
a.column_1
)
without knowing your real schema...based on your sample query, assuming your inner queries are correct (some minor syntax error). You might want to do something like this.
select *
FROM
(select a.column_1 as ID,a.column_2,COUNT(b.column_2) as Cnt1
from table_1 a left outer join table_2 b on a.ID=b.ID
group by a.column_1,a.column_2
) T1
INNER JOIN
(select a.column_1 as ID,COUNT(c.column_2) as Cnt2
from table_1 a left outer join table_3 c on a.ID=c.ID
group by a.column_1
) T2 ON T1.ID = T2.ID
sqlfiddle
You might want to replace select * with select T1.ID,T1.column_2,Cnt1,Cnt2 based on your comment.
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
SELECT
count(t1.id) AS c1
FROM
table2
LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
WHERE
table2.mode = 'ls'
GROUP BY
t1.id
c1 = 6 -> CORRECT!
SELECT
count(t2.id) AS c2
FROM
table2
LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
WHERE
table2.mode = 'ls'
GROUP BY
t1.id
c2 = 1 -> CORRECT!
SELECT
count(t1.id) AS c1,
count(t2.id) AS c2
FROM
table2
LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
WHERE
table2.mode = 'ls'
GROUP BY
t1.id
c1 = 6 -> CORRECT!
c2 = 6 -> WRONG!
How do I request both counts in one query, without getting wrong results?
I need to count two different requests at the same table (table1).
so, I'm using an alias for both request. (t1). Each alias-request is working fine alone. If I use both in the same query, i got wrong results.
count() will get you the number of records that are returned by your query. Since if you removed the counts and replaced it with * you would have 6 rows both of those counts are giving you 6.
Is there any reason why you cant use two sub selects and return the result of each of those?
So:
SELECT subQ1.c1, subQ2.c2 FROM
(SELECT count(t1.id) AS c1 FROM table2
LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
WHERE table2.mode = 'ls') as subQ1,
(SELECT count(t2.id) AS c2 FROM table2
LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
WHERE table2.mode = 'ls') as SubQ2;
I believe your problem on the full query is your group by function. You are grouping by t.id, thus a1.id will have a different count based on how many rows you have.
What I mean by this is if there are 6 rows in table t, then count is going to return 6 for table t; but also since there looks to be a 1 to 1 relation on table a, there are 6 matching rows in table a to the 6 matching rows in table t. such that
t.id = a.id
1 = 1
2= 2 ...etc.
Thus your count is returning rows versus the count you believe you should have? I believe sum function is what you want to use here.
You could try this...but I'm not really sure what you're trying to do.
SELECT (...)
count(CASE WHEN t1.uid = t3.uid THEN t1.id ELSE NULL END) AS CBanz,
count(CASE WHEN ta1.pid = t3.id THEN a1.id ELSE NULL END) AS CBanz1
FROM
t0
LEFT JOIN (...)
LEFT JOIN t1 ON (t1.uid = t3.uid)
LEFT JOIN t1 AS a1 ON (a1.pid = t3.id)
WHERE (...)