mysql - 我按类型分组并计数自连接表以获取摘要

标签 mysql sql

这是我的sql

select count(type), type
from tasks
group by type

这里有 4 行。

count(type) type
8           Trial
7           New
3           Service
4           Uninstall

如何在返回中得到一行结果

Trial   New Service Uninstall
8       7   3       4

我知道它必须自连接表。但是我无法准确地得到。

这是示例表数据

id  type        date
1   New         2017-10-07
2   Trial       2017-10-01
3   New         2017-10-02
4   Uninstall   2017-10-05
5   Trial       2017-10-06
6   Trial       2017-10-07

最佳答案

这是通过条件聚合完成的:

select
  sum(type = 'Trial') as trial,
  sum(type = 'New') as new,
  sum(type = 'Service') as service,
  sum(type = 'Uninstall') as uninstall
from mytable;

在 MySQL 中 true 为 1,false 为 0,因此我们可以使用 SUM 来计算匹配。

关于mysql - 我按类型分组并计数自连接表以获取摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139922/

相关文章:

java - Spring - 仅在保存/POST 时出现 'field list' 中的未知列(但读取/GET 有效...)

php - 统计按月份 w 分组的状态的 SQL 查询。修订制度

一次插入所有值的MySQL

mysql - 对 IN 使用多个 ='s?

java - sql异常:Parameter index out of range

Mysql正则表达式用数字搜索

mysql - 零售数据库设计 - 具有不同配件的多种产品

sql - Rails 3.2 事件记录连接 : Record not showing up

mysql - SQL - 缩短查询

android - 如何使用sqlite3从android应用程序中的表中提取数据?