繁体   English   中英

使用Mysql中需要的多个子查询进行查询

[英]Query with multiple subqueries required in Mysql

我在寻找一些查询帮助

这是下表数据

Name    Runs    Status
Ram         50  out
Ram         103 not out
Krish   51  out
Sam         15  out
Ram         15  out
Krish   78  not out

我希望有一个查询能给出以下结果

Name    Total   >100    >50&<100    TotalTimes  Notout 
Ram        168  1           1         3          1
Sam        15   0           0         1          0
Krish      129  0           2         2          1

我可以在Group By功能的帮助下编写查询以获取总计Totaltimes,其余的我一无所获

这是我提出的查询

select Name, sum(Runs) as total, count(*) as totalTimes
from tempTable 
where classID IN (Select classID from upcoming_Clases where classes_id=175) 
group by Name order by total desc 

我正在使用Mysql数据库

您可以将SUM()IF() SUM()一起使用来测试您的条件:

SELECT
    Name,
    SUM(Runs) AS Total,
    SUM(IF(Runs>100, 1, 0)) AS `>100`,
    SUM(IF(Runs>50 AND Runs<100), 1, 0) AS `>50&<100`,
    COUNT(*) AS TotalTimes,
    SUM(IF(Status='not out', 1, 0)) AS Notout
FROM tempTable
WHERE classID IN (SELECT classID FROM upcoming_Clases WHERE classes_id = 175)
GROUP BY Name
ORDER BY Total DESC

您可以使用案例来做到这一点:

select Name, 
       sum(Runs) as total, 
       count(case when Runs>100 then 1 end) `>100`,
       count(case when Runs>50 and Runs<100 then 1 end) `>50&<100`,
       count(*) as totalTimes,
       count(case when Status='not out' then 1 end) `Not Out`
from tempTable 
where classID IN (Select classID from upcoming_Clases where classes_id=175) 
group by Name order by total desc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM