sum multiple columns of same table in mysql - php

I am working on developing sports site.
In this site I've two tables one is tbl_team which stores the team details and another table is tbl_tournamentmatches which stores the details of different rounds of tournament matches.
In my tbl_tournamentmatches I'm storing team1_id, team2_id, team1_score and team2_score.
My Table having entry like this:
tbl_tournamentmatches
match_id team1_id team2_id team1_score team2_score
5 4 9 15 5
6 9 16 15 5
7 4 16 5 15
8 4 16 5 15
tbl_team
team_id team_title
4 KKR
9 RR
16 CSK
I want Result Should look like this:-
Team name Score
CSK 35
KKR 25
RR 20
I'd used this query :-
select * from
(
SELECT sum(team1_points) as totalpoints,t.team_title
from tbl_team t
left join tbl_tournamentmatches m
on t.team_id = m.team1_id
where tournament_id = 3 AND agegroup_id = 36
group by team1_id
union
SELECT sum(team2_points) as totalpoints,t.team_title
from tbl_team t
left join tbl_tournamentmatches m
on t.team_id = m.team2_id
where tournament_id = 3 AND agegroup_id = 36
group by team2_id
) s
But i got result like this :-
KKR 25
RR 15
RR 5
CSK 35
Any Help will be appreciated. Thanks in advance.

Do the joins to get the team and points for each match, and then do the sum on the results of that:-
SELECT team_title, sum(team_points) as totalpoints
FROM
(
SELECT team1_id AS team_id, team1_points AS team_points, t.team_title
FROM tbl_team t
LEFT JOIN tbl_tournamentmatches m
ON t.team_id = m.team1_id
WHERE tournament_id = 3 AND agegroup_id = 36
UNION ALL
SELECT team2_id AS team_id, team2_points AS team_points, t.team_title
FROM tbl_team t
LEFT JOIN tbl_tournamentmatches m
ON t.team_id = m.team2_id
WHERE tournament_id = 3 AND agegroup_id = 36
) s
GROUP BY team_id, team_title

try this query
SELECT t.team_name
,SUM(CASE
WHEN t.team_id = tn.team1_id THEN tn.team1_score
WHEN t.team_id = tn.team2_id THEN tn.team2_score
END) AS score
FROM team t
LEFT JOIN tournament tn ON t.team_id = tn.team1_id OR t.team_id = team2_id
GROUP BY t.team_name

You almost got it.
In your query I see fields that you don't include in your table (e.g. agegroup_id), but you only are a step of a solution: change your outter "select * from " for a: "select sum(totalpoints), team_title" and add a group by at the end: "group by team_title"
select sum(totalpoints) as totalpoints, team_title from
(
SELECT sum(team1_score) as totalpoints, t.team_title
from tbl_team t
join tbl_tournamentmatches m
on t.team_id = m.team1_id
--where tournament_id = 3 AND agegroup_id = 36
group by team1_id
union
SELECT sum(team2_score) as totalpoints, t.team_title
from tbl_team t
join tbl_tournamentmatches m
on t.team_id = m.team2_id
--where tournament_id = 3 AND agegroup_id = 36
group by team2_id
) s
group by team_title;

Use Union all to make all team and score as different rows.
Then use an Inner Join.
Query
select t2.team_title as TeamName,
sum(team_score) as Score
from
(
select match_id,team1_id as team_id, team1_score as team_score
from tblMatch
union all
select match_id,team2_id as team_id, team2_score as team_score
from tblMatch
)t1
join tblTeam t2
on t1.team_id = t2.team_id
group by t2.team_id;
SQL Fiddle

Related

How to select only latest added records avoiding duplicates

I need to select from the table competition_rounds the latest added records which are linked to the competition_seasons table with the season_id column, eg:
competition_rounds
id | name | season_id
1 Round A 20
2 Round B 20
3 Round A 21
4 Round B 21
competition_seasons
id | name | competition_id
20 2017/2018 40
21 2018/2019 40
I want return only:
round_id | round_name | season_id | season_name
3 Round A 21 2018/2019
4 Round B 21 2018/2019
the problem's that my query return all rounds available:
$sql = $this->db->prepare("SELECT max(r.id) AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r
JOIN competition_seasons s ON r.season_id = s.id
JOIN competition c ON s.competition_id = c.id
WHERE c.id = :competition_id
GROUP BY r.id
ORDER BY max(r.season_id) DESC");
$sql->bindParam("competition_id", 40);
$sql->execute();
$rounds = $sql->fetchAll();
return $response->withJson($rounds);
NB: The table competition simply contains a list of competition references.
If I understand correctly, you can use a subquery to return only the latest season from the seasons table:
SELECT r.id AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r JOIN
(SELECT s.*
FROM competition_seasons s
WHERE s.competition_id = :competition_id
ORDER BY s.id DESC
LIMIT 1
) s
ON r.season_id = s.id ;
Your question only mentions two tables, although the query has three. This is only based on the question.
You has no any competition columns in SELECT so you can just omit it from the query.
Take the last added (max(id)) season for a given :competition_id
SELECT r.id AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r
JOIN competition_seasons s ON r.season_id = s.id
WHERE s.id = (SELECT max(cs.id)
FROM competition_seasons cs
WHERE cs.competition_id = :competition_id)

multiple count and sum MySQL function returning wrong values with multiple joins in MySQL result

Table mpkids_students AS A
id BranchId Email Mobile StudentId
9497 25 mpsuraj2016#gmail.com 8700698773 25
9498 25 m016#gmail.com 8700698776 26
Table mpkids_student_image_gallery AS B
id like_count student_id
1 25 27
Table mpkids_visitors AS C
id student_id
1 9497
2 9497
3 9497
Table mpkids_visitors_count AS D
id visitor_count student_id
1 4 23
Table mpkids_image_likes AS E
id student_id
1 67
Table mpkids_relatives_data AS F
id student_id rel_email rel_mobile
1 9497 kushwahji#gmail.com 9009859691
2 9497 kushwah#gmail.com 7566403326
3 9497 kushwah#gmail.com 1236403326
4 9497 suraj#gmail.com 123640332
Table mpkids_paidstatus AS G
id student_id Received
1 9497 7500
2 9497 3000
3 9497 3000
MYSQL QUERY
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
SUM(G.Received) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
LEFT JOIN mpkids_paidstatus AS G ON G.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC
Result:
student_id images visits likes emails moibles Received
9497 0 3 NULL 4 5 202500
9498 0 0 NULL 1 1 NULL
Problem Explanation:
Received Field returning wrong value i have tried many queries but not getting solution
Received Field correct value 13500 for student_id = 9497
Please help me to find solution.
You are getting wrong output because, when you are joining based on studentid, you are getting multiple records from mpkids_paidstatus table for each student, which is adding up and returning a wrong output.
You can also write your query like following using subquery.
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
(select SUM(Received) from mpkids_paidstatus ps where ps.student_id=a.id) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC

mysql get last 2 records of table with 3 tables

I have 3 mysql tables (order , camp , user) as bellow values,
order_table
ID camp_id orderDate message
1 1 2015-01-01 ok
2 1 2015-02-01 ok
3 2 2015-03-01 not ok
4 3 2015-01-01 not ok
5 1 2015-04-01 not ok
6 2 2015-01-01 ok
7 3 2015-07-01 not ok
camp_table
camp_id camp_uid camp name
1 10 first camp
2 11 second camp
3 12 third camp
4 10 forth camp
user_table
uid uname
10 abc
11 xyz
12 wrt
i want to have result as bellow
uname,camp name,message
for last 2 records of each user from order_table for today order by orderDate
I want to join these tables to have uname from user_table and camp name from camp_table and message from order_table.
for today order by orderDate
Thanks
Select
ct.camp_name,
ut.uname,
ot.message FROM order_table as ot
LEFT JOIN camp_table as ct on ot.camp_id = ct.camp_id
LEFT JOIN user_table as ut on ct.camp_uid = ut.uid
order by ot.id desc
limit 2
SELECT
u.uname,
ct.camp_name,
ot.message
FROM
(
SELECT
*
FROM
order_table o1
WHERE
(
SELECT
COUNT(*)
FROM
order_table o2
WHERE
o1.camp_id = o2.camp_id
AND o2.ID >= o1.ID
) <= 2
) ot
INNER JOIN camp_table ct ON ct.camp_id = ot.camp_id
INNER JOIN user_table u ON ct.camp_uid = u.uid
ORDER BY
u.uname
Order By Date and join both table.
Select t1.camp_name, t2.uname,t3.message FROM order_table as t3
LEFT JOIN camp_table as t1 on t3.camp_id = t1.camp_id
LEFT JOIN user_table as t2 on t1.camp_uid = t2.uid
order by t3.orderDate desc
limit 2

Mysql request from two tables with counting

I have two tables
**users**
id name
1 Name1
2 Name2
**tasks**
id user_id title
1 1 Task1
2 1 Task2
3 2 Task3
My request:
SELECT
U.*,
COUNT(T.id) AS tasks_total
FROM
`#__users` AS U
LEFT JOIN
`#__tasks` AS T
ON
U.id = T.user_id
I think something wrong here...
I wan't to get results:
id name tasks_total
1 Name1 2
2 Name2 1
Thanks!
You forgot to group the result by id
SELECT
U.*,
COUNT(T.id) AS tasks_total
FROM
`#__users` AS U
LEFT JOIN
`#__tasks` AS T
ON
U.id = T.user_id
group by U.id
demo on sqlfiddle
You're mixing line functions and aggregate functions. One way around this is to have the aggregation done in a subquery:
SELECT
U.*,
tasks_total
FROM
`#__users` AS U
LEFT JOIN
(SELECT user_id, COUNT(*) AS tasks_total
FROM `#__tasks`
GROUP BY user_id) AS T
ON
U.id = T.user_id

MySQL display team standings from results table

I have two tables:
teams
---------------------
team_id team_name
---------------------
1 Lakers
2 Clippers
3 Grizzlies
4 Heat
results
...............................................................
game_id team_id1 team_id2 team1_score team2_score
1 1 2 20 30
2 1 3 40 50
3 2 1 50 60
4 4 2 20 30
5 1 2 20 30
My question is, how can I then create standings results for this tables based on results sorted by points, like this:
...............................................................
Position team_name total_points games_played
1 Lakers 140 4
2 Clippers 110 3
3 Grizzlies 50 1
4 Heat 20 1
I guess what you would like to do is something like this:
EDITED
SET #num :=0;
SELECT (#num := #num + 1) as Position,team_name,total_points,games_played
FROM (
SELECT teams.team_name, SUM(p) as total_points, count(*) as games_played
FROM (
SELECT team_id1 as id, team1_score as p FROM results
UNION ALL
SELECT team_id2 as id, team2_score as p FROM results
) t
INNER JOIN teams ON t.id = teams.team_id
GROUP BY id,teams.team_name ) t2
ORDER BY total_points DESC;
SQLFiddle is here : http://www.sqlfiddle.com/#!2/5bf2c/1
If you would like to display all teams, even if some teams did not play a single game, you could go like this:
SET #num :=0;
SELECT (#num := #num + 1) as Position,team_name,total_points,games_played
FROM (
SELECT
teams.team_name,
SUM(p) as total_points,
SUM(f) as games_played
FROM (
SELECT team_id1 as id, team1_score as p, 1 as f FROM results
UNION ALL
SELECT team_id2 as id, team2_score as p, 1 as f FROM results
UNION ALL
SELECT team_id as id, 0 as p, 0 as f FROM teams
) t
INNER JOIN teams ON t.id = teams.team_id
GROUP BY id,teams.team_name ) t2
ORDER BY total_points DESC;
SQLFiddle is here: http://www.sqlfiddle.com/#!2/8ecf5d/9
Hope this helps.
I may have renamed a couple of your columns... oh, and teams 1 and 2 are tied so you need to say a little more about how to resolve that...
SELECT t.*
, COUNT(*) p
, SUM(score) pts
FROM
(
SELECT home_team_id team_id,home_team_score score FROM results
UNION ALL
SELECT away_team_id,away_team_score FROM results
) x
JOIN teams t
ON t.team_id = x.team_id
GROUP
BY t.team_id
ORDER
BY pts DESC;
select team_id,team_name,sum(sc1) ,sum(ct1) from
(select team_id,teams.team_name,sc1,ct1 from
(select team_id1,sum(team1_score)as sc1,count(team_id1) as ct1 from results group by team_id1) as srtbl1,teams
where srtbl1.team_id1 =teams.team_id
union
select team_id,teams.team_name,sc2,ct2 from
(select team_id2,sum(team2_score)as sc2 ,count(team_id2) as ct2 from results group by team_id2) as srtbl2,teams
where srtbl2.team_id2 =teams.team_id) sctbl
group by team_id;
and I think you make a mistake in calculating .

Categories