mysql—在一个表上进行查询,以便在一个查询中获得2个计数

lmvvr0a8  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(229)

我在mysql中有两个表
表1(日期(完整日期)、应用程序id、类型(免费、付费))
表2(日期、年、月、日、季)
单个计数的查询是:

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      |
----------------------------------
wb1gzix0

wb1gzix01#

这里有一个选项 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 条款。

gmol1639

gmol16392#

试试这个:

SELECT
  d.year,
  SUM(CASE WHEN a.Type = 'Free' THEN 1 ELSE 0 END) AS free_count,
  SUM(CASE WHEN a.Type = 'Paid' THEN 1 ELSE 0 END) AS paid_count
FROM Table2 d -- Dates table
LEFT JOIN Table1 a -- Apps table
  ON d.Date_fk = a.Date
GROUP BY d.year;

这个 LEFT JOIN 保证在没有任何应用程序的情况下,你仍然可以获得这些年的结果。

相关问题