[英]How to count number of times each state appears in SQL table
I have a SQL table with three columns: name , date of birth , and current state . 我有一个包含三列的SQL表: 名称 , 出生日期和当前状态 。 I want to return a result-set with the number of times each state appeared in the original table.
我想返回一个结果集,其中包含每个状态在原始表中出现的次数。 The result-set will have 2 columns: state and count .
结果集将包含两列: state和count 。
I'm guessing I will need to use GROUP BY
or COUNT
but I haven't been able to put it together. 我猜我将需要使用
GROUP BY
或COUNT
但是我无法将其放在一起。
你可以这样
SELECT current_state, count(current_state) FROM table GROUP BY current_state
The following syntax will work for most SQL engines: 以下语法适用于大多数 SQL引擎:
SELECT expression1, expression2, ... expression_n, COUNT(aggregate_expression) FROM tables [WHERE conditions] GROUP BY expression1, expression2, ... expression_n [ORDER BY expression [ ASC | DESC ]];
Parameters or Arguments
参数或参数
expression1, expression2, ... expression_n
expression1,expression2,... expression_n
Expressions that are not encapsulated within the COUNT function and must be included in the GROUP BY clause at the end of the SQL statement.未封装在COUNT函数中并且必须包含在SQL语句末尾的GROUP BY子句中的表达式。
aggregate_expression聚合_表达
This is the column or expression whose non-null values will be counted.这是将计算非空值的列或表达式。
tables桌子
The tables that you wish to retrieve records from.您希望从中检索记录的表。 There must be at least one table listed in the FROM clause.
在FROM子句中必须至少列出一个表。
WHERE conditions条件
Optional.可选的。 These are conditions that must be met for the records to be selected.
这些是选择记录必须满足的条件。
ORDER BY expressionORDER BY表达式
Optional.可选的。 The expression used to sort the records in the result set.
该表达式用于对结果集中的记录进行排序。 If more than one expression is provided, the values should be comma separated.
如果提供了多个表达式,则这些值应以逗号分隔。
ASCASC
Optional.可选的。 ASC sorts the result set in ascending order by expression.
ASC按表达式升序对结果集进行排序。 This is the default behavior, if no modifier is provider.
如果没有提供者,则这是默认行为。
DESC数据中心
Optional.可选的。 DESC sorts the result set in descending order by expression.
DESC按表达式对结果集进行降序排序。
11个
Refer to documentation for the specific engine used: 请参阅文档以了解所使用的特定引擎:
T-SQL/SQL Server T-SQL / SQL服务器
...etc ...等等
For the " question " 对于“ 问题 ”
I have a SQL table with three columns: name, date of birth, and current state.
我有一个包含三列的SQL表:名称,出生日期和当前状态。 I want to return a result-set with the number of times each state appeared in the original table.
我想返回一个结果集,其中包含每个状态在原始表中出现的次数。 The result-set will have 2 columns: state and count.
结果集将包含2列:状态和计数。
such a query could be constructed like this: 这样的查询可以这样构造:
SELECT current_state as state, count(*) as count
FROM data
GROUP BY current_state
See an example of this in this SQLfiddle . 在此SQLfiddle中查看此示例 。
1 https://www.techonthenet.com/sql/count.php 1 https://www.techonthenet.com/sql/count.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.