简体   繁体   English

sql count结果大于特定数目

[英]sql count where result is greater than certain number

The following query will sum the goals for each match: 以下查询将汇总每次比赛的目标:

SELECT
  SUM(Goals)
FROM `Team Match Table`
WHERE Match_Id IN (SELECT ID FROM Match Table
  WHERE HomeTeam_ID = (SELECT ID FROM `Team Table` WHERE `Team Name` = 'Aberdeen')
  OR AwayTeam_ID = (SELECT ID FROM `Team Table` WHERE `Team Name` = 'Aberdeen'))
GROUP by Match_Id

Is it possible to count how many of the results are greater than a certain number? 是否可以计算多少个结果大于一定数目?

Use SUM() on the condition to give you the count: 在条件上使用SUM()可以给您计数:

SELECT
    SUM(Goals) total_goals,
    SUM(Goals > 5) over_5_goals_count
FROM `Team Match Table`
WHERE Match_Id IN (SELECT ID FROM Match Table
  WHERE HomeTeam_ID = (SELECT ID FROM `Team Table` WHERE `Team Name` = 'Aberdeen')
  OR AwayTeam_ID = (SELECT ID FROM `Team Table` WHERE `Team Name` = 'Aberdeen'))
GROUP by Match_Id

This works (with mysql only), because mysql treats true as 1 and false as 0 , so summing the result of a condition gives you the count of the number of times it was true. 这是可行的(仅适用于mysql),因为mysql将true视为1 ,将false视为0 ,因此对条件的结果求和就可以得到它为true的次数。

I chose > 5 as the condition. 我选择> 5作为条件。 You can use whatever threshold you want. 您可以使用任何所需的阈值。

Is the table name 'Team Match Table is correct' ? 表格名称“ Team Match Table是正确的”吗? As sql will not allow you to create a table name with space . 由于sql不允许您使用空格创建表名。

Query it in a perfect format . 以完美的格式查询它。

select sum(goals) from team_match_table where match_is in (select id from match table where hometeam_id in (select id from team_table where team_name='Aberdeen'or awayteam_id in (select id from team_table where team_name='Aberdeen'))) ; 从match_所在的team_match_table中选择sum(goals)(从匹配表中选择hometeam_id所在的id(从team_table那里选择team_name ='Aberdeen'的id或awayteam_id in(从team_table那里选择team_name ='Aberdeen')的ID)));

Rather than giving a condition you can use a specific values in a table to pull out perfect result . 除了给出条件外,您还可以在表中使用特定的值来得出理想的结果。

Just list out the tables you have , its common column as well 只需列出您拥有的表,以及其公共列

Try; 尝试;

SELECT Match_id, SUM(`Goals`)
FROM `Team Match Table`
WHERE `Match_Id` IN (SELECT `ID` FROM `Match Table`
                 WHERE `HomeTeam_ID` = (SELECT `ID` FROM `Team Table`
                                        WHERE `Team Name` = 'Aberdeen')
                    OR `AwayTeam_ID` = (SELECT `ID` FROM `Team Table`
                                        WHERE `Team Name` = 'Aberdeen'))
GROUP by `Match_Id`
HAVING SUM('Goals') >= DesiredNumber --Change DesiredNumber to a numeric value you wish to filter by

I've put the Match_id in the returned columns so that you can tell which matches have the number of goals you want to return. 我将Match_id放在返回的列中,以便您可以判断出哪些比赛具有要返回的目标数。 It will also tell you the number of goals in that match 它还会告诉您该比赛中的进球数

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

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