[英]How do I create a column in postgresql to count different values in the same cells of a column that are in varchar format?
How do I count different values in a cell of a column and put that count in a new column?如何计算一列单元格中的不同值并将该计数放入新列中?
for example:例如:
car/bike/truck/pickup/trailer/jeep
I want to be able to create a column like 'count of vehicle' with a corresponding value of 6. This is Postgres by the way我希望能够创建一个类似“车辆计数”的列,其对应值为 6。顺便说一下,这是 Postgres
You can count different values by SELECT COUNT(DISTINCT vehicle) FROM table;
您可以通过
SELECT COUNT(DISTINCT vehicle) FROM table;
and set some value to column by UPDATE table SET different = val
.并通过
UPDATE table SET different = val
为列设置一些值。
You can capture the names between slashes as a set using a regular expression.您可以使用正则表达式将斜线之间的名称捕获为一组。 Then, you can count the size of the set.
然后,您可以计算集合的大小。
For example:例如:
select count(*) from (
select regexp_matches('car/bike/truck/pickup/trailer/jeep',
'([^/]+)', 'g')
) x
Result:结果:
count
-----
6
See running examplt at db<>fiddle .请参阅在db<>fiddle运行示例。
You can turn that value into an array, then count the number of array elements:您可以将该值转换为数组,然后计算数组元素的数量:
select cardinality(string_to_array(the_column, '/')) as vehicle_count
from the_table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.