Join 2 Select Queries in a Same Table in MySql - mysql

I have a Table Name Called tbl_events and it does have following columns
Id,Event_Name, District,Branch_Type,Points
I need a Sum of Points Column Where Branch_Type=2; and Sum of Points Divided by 10 Where Branch_Type=2 after that I have to Add those Two Values And Group that Result by District and Order by Desc. I tried this Query but Seems to something wrong Can anyone help, please?
Select (t1.B_Points + t2.D_Points) as T_Points,District From
(Select Sum(Points)*.1 as B_Points ,District From tblstudents Where Branch_Type=3 group by District)t1
Left Join(Select Sum(Points) as D_points, District From tblstudents Where Branch_Type=2 group by District)t2 on
(t1.District=t2.District) Order by Desc

You need to add column alias T_Points in order by
Select (t1.B_Points + t2.D_Points) as T_Points,District
From
(
Select Sum(Points)*.1 as B_Points ,District From tblstudents
Where Branch_Type=3 group by District
)t1
Left Join
(
Select Sum(Points) as D_points, District From tblstudents
Where Branch_Type=2 group by District
)t2 on t1.District=t2.District
Order by T_Points Desc

You seem to just want conditional aggregation:
select district,
sum(case when branch_type = 3 then 0.1 * points
when branch_type = 2 then points
else 0
end) as t_points
from tblstudents
group by district;
If you want to order by the points descending, then add:
order by t_points desc
Note: This assumes that you want districts that have neither branch type. If that is not an issue, move the logic to the where clause:
select district,
sum(points * (case when branch_type = 3 then 0.1 else 1.0 end) as t_points
from tblstudents
where branch_type in (2, 3)
group by district
order by t_points desc;

Related

Top 10 players with the highest batting average

Batting average = total number of runs scored / number of times out.
Here we need to make sure to include run outs (on non-striker end)
Output like :
Batsman_name Average
KL Rahul 44
Error:
Error in SQL statement: AnalysisException: cannot resolve 'batsman_runs' given input columns: [_auto_generated_subquery_name.Batsman]; line 1 pos 21;
'Sort ['Average DESC NULLS LAST], true
select Batsman_, sum(batsman_runs)/count(player_dismissed) as Average
from
(
(select batsman as Batsman_ from IPL_BALL_BY_BALL)
union all
(select non_striker as Batsman_ from IPL_BALL_BY_BALL)
)
group by Batsman_
order by Average desc;
because from your subquery ( result of union) you only returning "Batsman_" column. you have to retunr all the column you need :
select Batsman_, sum(batsman_runs)/count(player_dismissed) as Average
from
(
(select batsman as Batsman_,batsman_runs,player_dismissed from IPL_BALL_BY_BALL)
union all
(select non_striker as Batsman_,batsman_runs,player_dismissed from IPL_BALL_BY_BALL)
)
group by Batsman_
order by Average desc;
select Batsman_, sum(batsman_runs)/count(player_dismissed) as Average from
((select batsman as Batsman_,batsman_runs,player_dismissed from IPL_BALL_BY_BALL) union all (select non_striker as Batsman_,batsman_runs,player_dismissed
from IPL_BALL_BY_BALL))
group by Batsman_ order by Average desc;
You forgot fields "batsman_run & player_dismissed" in your inner sql

How to get the ID of the max counted user in Order table

I have a table with
orderNumber(pk) , customerNumber , comment
I have to count the maximum order placed by a user and show its user ID and MAX count . I have following Query
It shows the count Right but it takes the first CustomerNumber in the table
SELECT maxCount.customerNumber , MAX(`counted`) FROM
(
SELECT customerNumber, COUNT(*) AS `counted`
FROM `orders`
GROUP BY `customerNumber`
)as maxCount
Thanks & regards
Just use ORDER BY with your inner query:
SELECT customerNumber, COUNT(*) AS `counted`
FROM `orders`
GROUP BY `customerNumber`
ORDER BY COUNT(*) DESC
LIMIT 1
If you want to return all customer numbers in the event of a tie, you can use a HAVING clause with a subquery which identifies the maximum count:
SELECT customerNumber, COUNT(*) AS counted
FROM orders
GROUP BY customerNumber
HAVING COUNT(*) = (SELECT MAX(t.counted) FROM (SELECT COUNT(*) AS counted
FROM orders
GROUP BY customerNumber) t)
Demo here:
SQLFiddle

SQL SCORE RANKING

I'm working with score ranking on my app for all user score. My problem is I don't know how to return one row for each stud_num.
My query:
SELECT * FROM score WHERE assess_type = 'professional' ORDER BY total_score DESC.
Result:
As you can see I have 3 stud_num and I only want one row per stud_num and the highest score of it.
You can use correlated query like this:
SELECT * FROM score t
WHERE t.assess_type = 'professional'
AND t.total_score = (select max(s.total_score)
from score s
where t.stud_num = s.stud_num)
group by stud_num
The option given by #sagi is good:
SELECT * FROM score t
WHERE t.assess_type = 'professional'
AND t.total_score = (select max(s.total_score)
from score s
where t.stud_num = s.stud_num)
group by stud_num
Another option would be to use an inner join and group by together.
The resulting query would become:
select * from score a
inner join (
SELECT stud_num, max(total_score) tscore FROM `score` group by stud_num) b
on a.stud_num = b.stud_num and total_score= tscore
group by a.stud_num
try it out at sqlfiddle
Use the MAX and GROUP BY functions like this:
SELECT score_id, stud_num, assess_type, total_item, MAX(total_score), average, date_taken
FROM score
WHERE assess_type = 'professional'
GROUP BY stud_num
ORDER BY 5 DESC
Here's my the ans:
SELECT score_id, stud_num, assess_type, total_item, MAX( total_score )
FROM score
WHERE assess_type = 'professional'
GROUP BY stud_num, total_item
ORDER BY MAX( total_score ) DESC

MySQL GROUP BY each comma separated value

Before anyone comments, I did not design this database with comma separated values :)
I have spent time trying to find the answer but all I could find was GROUP_CONCAT() which seemed to do the opposite of what I wanted.
I would like to GROUP BY each of the values within the comma separated value field.
SELECT round(avg(DATEDIFF( dateClosed , dateAded ) * 1.0), 2) AS avg, department
FROM tickets GROUP BY assignedto
the assignedto field is the comma separated value field
row1 54,69,555
row2 54,75,555
row3 75,555
DESIRED OUTPUT: an average rounded figure for each value in assignedto field grouped.
EDIT - TRYING TO TAKE THIS TO THE NEXT LEVEL:
I want to include the ticket answer table to get the first response for that ticket, use its datetime field to work out the average response time for each user.
SELECT a.id as theuser, round(avg(DATEDIFF( ta.dateAded , t.dateAded ) * 1.0), 2) as avg
FROM tickets t join
mdl_user a
on find_in_set(a.id, t.assignedto) > 0
INNER JOIN (SELECT MIN(ta.dateAded) as started FROM ticketanswer GROUP BY ta.ticketId) ta ON t.id = ta.ticketId
GROUP BY a.id ORDER BY avg ASC
Yuck. You can do this, assuming you know the maximum number of assignments. Here is an approach:
select substring_index(substring_index(assignedto, ',', n.n), ',', -1) as assignedto,
round(avg(DATEDIFF( dateClosed , dateAded ) * 1.0), 2) as avg
from tickets t join
(select 1 as n union all select 2 union all select 3)
on length(assignedto) - length(replace(assignedto, ',', '')) < n.n
group by substring_index(substring_index(assignedto, ',', n.n), ',', -1);
Or, an easier way if you have a list of assigned values, say in an AssignedTo table:
select a.assignedto, round(avg(DATEDIFF( dateClosed , dateAded ) * 1.0), 2) as avg
from tickets t join
assignedto a
on find_in_set(a.assignedto, t.assignedto) > 0
group by a.assignedto;
I'm sorry you have to deal with this malformed database structure.

Find student with the maximum average mark

i have tried a lot without success, i want to display only the maximum average of student marks from the list of student as shown on the table below.
My table
i want to get the result as below
expected output
what i have done so far
SELECT MAX(a.Total_Qty) As TotalMax,a.studentId
FROM(
SELECT AVG( s.marks ) AS Total_Qty,s.studentId
FROM results s
WHERE s.stream = 'Form One'
GROUP BY s.studentId) AS a
Inner query will give you the list of averages for each student.
Then we order (descending) by their average score and finally we get the top 1 (Limit 1)
SELECT a.studentId, a.Total_Qty as MaxAvg
FROM(
SELECT AVG( s.marks ) AS Total_Qty,s.studentId
FROM results s
WHERE s.stream = 'Form One'
GROUP BY s.studentId)
AS a
Order by a.Total_Qty Desc
Limit 1
Alternatively:
SELECT AVG( s.marks ) AS Total_Qty,s.studentId
FROM results s
WHERE s.stream = 'Form One'
GROUP BY s.studentId
Order By AVG( s.marks ) Desc
Limit 1
(UNTESTED) I hope it helps
if you are using MSSQL :
SELECT TOP(1) studentId, AVG(marks) FROM results GROUP BY studentId
ORDER BY MAX(AVG(marks)) Desc
if you are using SQL :
SELECT studentId, AVG(marks) FROM results GROUP BY studentId
ORDER BY MAX(AVG(marks)) Desc Limit 0,1