【问题标题】:Query count at the column with delimiter带有分隔符的列的查询计数
【发布时间】:2019-10-29 17:13:41
【问题描述】:

我有如下数据列。

A1
A2
A3
A1/B1
A1/B2
A1/B1/C1

通常我复制然后到excel并使用文本到列功能然后计数。 我可以使用查询命令直接在服务器上计算它们吗? 示例计数 我如何计算总数 没有/的是3 其中有一个 / 是 2 其中有两个 / 是 1

针对 SQL 查询进行了更新

select ( len(colA) - len(replace(colA, '/', '')) ) as num_slashes 
from DBO.table1  

得到结果

怎么算0有3个数,1有2个数,2有1个数?

0
0
0
1
1
2

【问题讨论】:

  • 不要存储这样的数据(/分隔的项目)。只会给你带来很多麻烦。
  • 什么问题?它是由建筑师设计的。

标签: sql postgresql


【解决方案1】:

我认为 Postgres 没有像 regexp_count() 这样的功能。一种方法是两个字符串的长度不同。您可以使用:

select ( length(col) - length(replace(col, '/', '')) ) as num_slashes,
       count(*)
from t
group by num_slashes
order by num_slashes;

也许一种更像 Postgres-y 的方式将值转换为数组,然后获取长度:

select array_length(string_to_array(col, '/'), 1) - 1

【讨论】:

  • 或者只是与string_to_array分开。无需涉及正则表达式。
  • mssql 不支持长度和字符串转数组功能。可以使用任何替代功能吗?
  • @user12158726 。 . .等效函数为len()。
  • len() 可以使用,但仍然 'num_slashes' 返回无效的列名 'num_slashes'。
  • select (len(itemid) - len(replace(itemid, '/', '')) ) as num_slashes from item.items group by num_slashes
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 2014-07-08
  • 1970-01-01
  • 2015-11-13
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多