我有下表:
ID custom_1 custom_2
+----+------------------------+------------------------
1 value_1 NULL
2 value_2 value_1
3 value_3 value_4
4 NULL value_4
我想构建一个查询来获取以下输出:
value count
+------------------------+------------------------
value_1 2
value_2 1
value_3 1
value_4 2
我知道我可以GROUP BY几个字段,但我认为在这种情况下这不是这样做的方法。我是否必须使用UNION?
答案 0 :(得分:2)
您可以使用union all
运算符在单个结果列中获取这两列,然后按其分组:
SELECT custom, COUNT(*)
FROM (SELECT custom_1 AS custom
FROM mytable
UNION ALL
SELECT custom_2 AS custom
FROM mytable) t
GROUP BY custom