mysql - 查询表以在单个查询中获得 2 个计数。
问题描述
我在 MySQL 中有两个表
table1 (Date(full_date), app_id, type(free,paid))
table2 (Date_fk, Year, month, day, quater)
单次查询是:
select Year, count(*)
from Table1, Table2
where Table1.Date = Table2.Date and Table1.Type='Free'
GROUP BY YEAR
---------------------
| year | free_count |
---------------------
| 2019 | 10 |
---------------------
我想要输出为
---------------------------------
| year | free_count | Paid_count |
----------------------------------
| 2019 | 10 | 12 |
----------------------------------
解决方案
这是使用的一个选项conditional aggregation
:
select year,
count(case when t1.type='free' then 1 end) as freecount,
count(case when t1.type='paid' then 1 end) as paidcount
from table1 t1
join table2 t2 on t1.date = t2.date
group by year
另外请看一下join
语法。一般来说,我强烈建议不要在您的from
子句中使用逗号。
推荐阅读
- python - 如何通过tkinter输入框将多个值从一个函数返回到另一个?(ValueError:无法将字符串转换为浮点数:)
- angular - TypeScript 在函数声明中使用 this
- angular - Hapi js 作为代理服务器来处理 api 调用
- java - 使用默认格式的 Elasticsearch 日期解析问题
- r - Plotly:如何为每个数据设置背景颜色
- reactjs - 如何在 redux 选择器中按 id 获取帖子
- php - 将产品显示在它们所属的类别之下
- swift - 如果枚举的案例具有关联类型,是否可以在没有关联数据的情况下获取案例名称?
- windows - 将错误代码从子 cmd 提示符批量返回到其父 cmd 提示符
- java - 如何让计时器在后台运行以在特定时间段后执行操作?