Select 每个不同的字段对应于同一 table 中的另一个字段

Select each distinct field that is corresponds to another field in the same table

我在从 table.

中提取数据时遇到问题

假设我有一个 table 比如:

t_stat 包含以下列:statId、userId、国家/地区、installerId、日期。

例如值:

1, 1, Belgium, 1, 2014-04-06 18:19:03 ||
2, 2, Germany, 2, 2013-05-07 18:19:03 ||
3, 3, Italy, 3, 2018-06-08 18:19:03

我需要的结果是: 我需要选择每个不同的国家,并计算它在每个日期的安装量。它应该是这样的:9行

2014-04-06 18:19:03 Belgium 1
2014-04-06 18:19:03 Germany 0
2014-04-06 18:19:03 Italy 0

2013-05-07 18:19:03 Belgium 0
2013-05-07 18:19:03 Germany 1
2013-05-07 18:19:03 Italy 0

2018-06-08 18:19:03 Belgium 0
2018-06-08 18:19:03 Germany 0
2018-06-08 18:19:03 Italy 1

有什么办法可以解决吗?

如果您不需要具有零值的行,这是微不足道的。

  SELECT DATE(date) date, country, COUNT(*) n
    FROM inst
  GROUP BY DATE(date), country
  ORDER BY date, country

但你确实需要它们。所以:

首先,您需要将(非规范化的)原始数据拆分为三个虚拟 table 以供参考。

这个虚拟 table 给你你的国家。

  SELECT DISTINCT country FROM inst

这为您提供了日期。

  SELECT DISTINCT DATE(date) date FROM inst

这会为您提供每个国家/地区每个日期的操作次数。

  SELECT DATE(date) date, country, COUNT(*) n

然后你需要将这三个虚拟table连接在一起。使用 LEFT JOIN 作为最后一个,这样零值就不会被抑制。并且,使用 IFNULL 显示零而不是空值。

SELECT  c.country, d.date, IFNULL(i.n,0) n
  FROM (
     SELECT DISTINCT country FROM inst
        ) c
  JOIN (
      SELECT DISTINCT DATE(date) date FROM inst
       ) d ON 1=1
  LEFT JOIN (
      SELECT DATE(date) date, country, COUNT(*) n
        FROM inst
      GROUP BY DATE(date), country
       ) i ON c.country = i.country AND d.date = i.date
 ORDER BY d.date, c.country

这是一个例子。 https://www.db-fiddle.com/f/vab5mvJepWn2YFLJ28kGxA/0