SQL:获取2个表中的字符串出现次数

时间:2018-08-02 03:21:51

标签: sql sqlite

我有两个表,每个表包含一个称为符号的列。

我想查询两个表,并得到一个包含每个符号及其在每个表中出现的次数的列表,如下例所示:

Symbol | Count
a | 2
b | 6
c | 7

以下是我目前在查询方面遇到的问题,但没有得到想要的结果。

SELECT one.symbol, COUNT(*) FROM one
JOIN two GROUP BY one.symbol,two.symbol;

这最终会多次列出所有符号,并且计数非常大。

我也尝试过:

SELECT orders.symbol, COUNT(orders.symbol) FROM orders
JOIN executions GROUP BY orders.symbol;

这会像我想要的那样列出每个符号一次,但是它只显示一张表中的计数两次(示例计数为1,并且显示11)

1 个答案:

答案 0 :(得分:0)

在内部子查询中将两个表合并为一个表,然后将其总数相加...

SELECT 
    symbol,
    SUM(symbol_count)
FROM (
    SELECT
        symbol,
        COUNT(symbol) as symbol_count
    FROM
        table_one
    GROUP BY
        symbol

    UNION ALL

    SELECT
        symbol,
        COUNT(symbol) as symbol_count
    FROM
        table_two
    GROUP BY
        symbol
) AS symbol_counts
GROUP BY
    symbol

更新: 要回答评论中提出的问题,并排进行计数:

SELECT
    symbol,
    COALESCE(table_one.symbol_count, 0) AS table_one_count,
    COALESCE(table_two.symbol_count, 0) AS table_two_count
FROM
    (SELECT
        symbol,
        COUNT(symbol) as symbol_count
     FROM
        table_one
     GROUP BY
        symbol) AS table_one
   FULL JOIN
    (SELECT
        symbol,
        COUNT(symbol) as symbol_count
     FROM
        table_two
     GROUP BY
        symbol) AS table_two
   ON table_one.symbol = table_two.symbol

FULL JOIN确保如果其中一个表缺少其中一个符号,则仍然可以选择该符号。 COALESCE将确保如果其中之一丢失(返回NULL,则将其替换为零。