Mysql中需要多个子查询的查询

Mysql中需要多个子查询的查询,mysql,database,Mysql,Database,我正在寻找一些查询帮助 以下是数据表 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

我正在寻找一些查询帮助

以下是数据表

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
我正在使用Mysql数据库

您可以与一起使用来测试您的条件:

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
选择
名称
总计(运行次数),
求和(如果(运行>100,1,0))为“>100”,
总和(如果(运行次数>50和运行次数50&),您可以与一起使用来测试您的标准:

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
选择
名称
总计(运行次数),
求和(如果(运行>100,1,0))为“>100”,

求和(如果(运行>50和运行50&),您可以使用case:

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
选择名称,
总计(运行次数),
计数(运行>100时为1结束)`>100`,

计数(运行>50和运行50时的大小写&您可以使用大小写:

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
选择名称,
总计(运行次数),
计数(运行>100时为1结束)`>100`,

计数(当Runs>50和Runs50&使用JOIN而不是IN时,假设在即将到来的类上每个类ID只有一条记录。因为如果给定的类ID在即将到来的类上有多条记录,它将相应地乘以总和和计数值。@MarkBannister:同意。我将保留
S而不是删除我的答案嗯(如果(…)
作为
计数(CASE…)
的替代方案-虽然我认为您的更清楚(因此给出+1),但此表单可能对OP/其他人可能想要执行的其他查询有指导意义。我认为它们都是有效答案,所以在联接更改为IN后我对您的进行了投票。我同意
总和(如果(
是一种很有用的技术。使用JOIN而不是IN假设在即将到来的类上每个类ID只有一条记录。因为如果给定的类ID在即将到来的类上有多条记录,它会相应地将总和和计数值相乘。@MarkBannister:同意。我将保留
SUM(IF(..)
作为
计数(CASE…)
的替代方法-虽然我认为您的更清楚(因此给出+1),但此表单可能对OP/其他人可能希望执行的其他查询有指导意义。我认为它们都是有效答案,因此在联接更改为IN后我对您的答案进行了投票。我同意
SUM(如果(
是一种有用的技术。我怀疑你实际上是想让你的第三个输出列为
=100
;否则正好有一个世纪的击球手将不计入半个世纪或世纪列中。我怀疑你实际上是想让你的第三个输出列为
=100
;否则正好有一个世纪的击球手将不计入半个世纪或世纪列中I’我不算在半个世纪或世纪栏中。