【问题标题】:Grouping 3 columns into 1 column and generating count SQL将 3 列分组为 1 列并生成计数 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 并为此计数。

标签: mysql sql group-by count union


【解决方案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 

【讨论】:

  • 还有其他方法吗?
  • 谢谢!它按我的预期工作。
猜你喜欢
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多