mysql - 计算2列Mysql
问题描述
计算 2 列
这是我的桌子
Table A
|----------------------|---------------------|------------------|
| id | typec NOM |
|----------------------|---------------------|------------------|
| 1 | Plat | A |
|----------------------|---------------------|------------------|
| 2 | Steeple-chase | B |
|----------------------|---------------------|------------------|
| 3 | Haies | C |
|----------------------|---------------------|------------------|
我希望输出为:
+------------+--------+--------------+---------+-----------+
| nom | Plat |Steeple-chase | Haies | ALL |
+------------+--------+--------------+---------+-----------+
| A | 10 | 2 | 8 | 20 |
+------------+--------+--------------+---------+-----------+
| B | 100 | 50 | 50 | 100 |
+------------+--------+--------------+------+--------------+
| C | 5 | 5 | 5 | 15 |
+------------+--------+--------------+---------+-----------+
目前,我运行此查询,但结果不好
SELECT nom, typec, count(*) AS count
FROM p_mu.cachedate
GROUP BY nom, typec;
谢谢你的帮助...
解决方案
我怀疑您正在寻找枢轴/条件聚合(如果您发布与所需结果匹配的示例数据,我会更确定)
SELECT nom, sum(case when typec ='plat' then 1 else 0 end) as 'plat',
sum(case when typec ='steeple_chase' then 1 else 0 end) as 'steeple-chase',
sum(case when typec ='hais' then 1 else 0 end) as 'hais',
count(*) AS 'all'
FROM p_mu.cachedate
GROUP BY nom;
推荐阅读
- postgresql - PostgreSQL - 根据字段的值将表上的删除/更新限制为特定角色
- postgresql - 重复 PostgreSQL 错误代码名称 'string_data_right_truncation'
- ruby-on-rails - WebKit/Chrome 时间戳转换为 Ruby/Rails
- docker - Dockerfile ~ 添加 Windows 文件夹的正确语法
- java - ORACLE 报告:REP-1814:报告无法格式化。对象垂直无法放入位置 B_15
- laravel - Laravel - 没有这个框架直接访问 PHP
- windows - Gzip使用批处理和7zip将带有子文件夹的多个文件压缩到每个名称中
- java - 泛型对象参数的类型问题
- android - kotlin 中的 DateFormat 在不同的设备中给出不同的输出
- javascript - Angular 5 在 textarea 上突出显示额外内容 | 输入文本区域,在 div 中显示 | 滚动问题