我在查询时遇到困难,我需要计算某个值的所有可能出现次数并显示它。想象一下,我有一张这样的表
----------------------------
| field1 | field2 | field3 |
----------------------------
| a | a | b |
----------------------------
| c | b | a |
----------------------------
所以,我希望我的查询返回这样的内容:
-----------------------
| value_found | count |
-----------------------
| a | 3 |
-----------------------
| b | 2 |
-----------------------
| c | 1 |
-----------------------
我试过一个几乎给了我所需要的东西,但它太长了,可能不太理想,所以非常感谢你。
答案 0 :(得分:2)
您可以使用union all
和group by
:
select field, count(*)
from (select field1 as field from t union all
select field2 as field from t union all
select field3 as field from t
) t
group by field;