如何查找可以存在于 2 列中的特定数字的计数

How to find the count of a particular number that can exist in 2 columns

我有一个 table,其中包含描述调用的 table。因此有一个 to 列和一个 from 列。问题是我想要每个号码发送的消息总数,可以是fromto。请参阅上面的 table 以获得视觉效果。

我希望最后的 table 显示 A : 3 、 B: 2 、 C:1 和 D:1.

如何计算 2 列中的数字并将它们相加?

您可以逆透视数据并聚合:

select person, count(*) as num_calls
from ((select from as person from t) union all
      (select to as person from t
     ) c
group by person;

请注意,fromto 是非常非常糟糕的列名称,因为它们是 SQL 关键字。我没有在查询中转义它们,因为这只会使查询混乱,我假设真正的列有更好的名称。

一个解决方案是首先 UNION ALL 两个聚合查询来收集两个不同列中每个值的出现次数,然后在外部查询中对结果求和,例如:

SELECT val, SUM(cnt) cnt
FROM (
    SELECT `from` val, COUNT(*) cnt FROM mytable GROUP BY `from`
    UNION ALL
    SELECT `to`, COUNT(*) FROM mytable GROUP BY `to`
) x
GROUP BY val

demo on DB Fiddle 与您的示例数据 returns:

| val | cnt |
| --- | --- |
| A   | 3   |
| B   | 2   |
| C   | 1   |
| D   | 1   |
| E   | 1   |