将 3 列分组为 1 列并生成计数 SQL

Posted

技术标签:

【中文标题】将 3 列分组为 1 列并生成计数 SQL【英文标题】:Grouping 3 columns into 1 column and generating count SQL 【发布时间】:2021-11-06 08:09:29 【问题描述】:

我有一个表,其中包含 3 列(myColumnX、myColumnY、myColumnZ)具有相同类型的值。

我正在尝试生成一个奇异列,其中包含所有 3 列中的值以及该列中每个值的计数。

这里是示例数据:

myColumnX myColumnY myColumnZ
a b c
b c d
b a d
e b c

我需要一个新列,这样我就可以分组并生成计数;输出需要是:

newColumn count
a 2
b 4
c 3
d 2
e 1

我如何得到这个结果?我在使用 UNION ALL 吗?

谢谢。

【问题讨论】:

是的,您也可以使用 union all 并为此计数。 【参考方案1】:

一种方式:

select newColumn , count(*) as count
from ( 
          select myColumnX as newColumn from table 
union all select myColumnY as newColumn from table 
union all select myColumnZ as newColumn from table 
) t
group by newColumn 

【讨论】:

还有其他方法吗? 谢谢!它按我的预期工作。

以上是关于将 3 列分组为 1 列并生成计数 SQL的主要内容,如果未能解决你的问题,请参考以下文章