首页 > 解决方案 > 查询表以在单个查询中获得 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      |
----------------------------------

标签: mysqlsql

解决方案


这是使用的一个选项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子句中使用逗号。


推荐阅读