在表上查询以在单个查询中获得2个计数。

时间:2018-12-14 00:58:21

标签: mysql sql

我在MySQL中有两个表

  

表1 (日期(完整日期),app_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      |
----------------------------------

2 个答案:

答案 0 :(得分:3)

以下是使用let mutable lines=new ResizeArray<string>() let paramLines= if File.Exists(maincfPath) then lines=File.ReadAllLines(maincfPath) else Environment.Exit(0) 的一种选择:

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子句中不要使用逗号。

答案 1 :(得分:1)

尝试一下:

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确保您在没有任何应用的情况下仍能获得当年的结果。