如何获取postgres中字段的计数?
How to get the count of the field in postgres?
我有一个tableorders
,它的结构是这样的:
create table orders (id serial primary key, created_at timestamp, updated_at timestamp, product_id varchar[]);
我为 product_id 我正在插入这样的数据:
insert into orders values (1,now(),now(),'{"1","2"}');
product_id
包含按特定订单订购的不同产品。每个 product_id
.
在 products
table 中都有一个条目
现在我想获取特定订单的 product_id
计数。
示例:对于我所做的上述插入,我应该得到如下内容:
Id Count
1 2
postgresql怎么可能?
编辑:抱歉弄乱了 create table
查询。这是一个 varchar[] 而不是 varchar(255)
您可以将值转换为数组并测量值的数量:
select o.*, cardinality(product_id)
from orders o
DDL:
CREATE TABLE tbl1 (id integer, count json);
INSERT INTO tbl1 (id, count) values (1, '["1", "2"]'::json), (2, '["3", "45"]');
查询:
SELECT id, sum(json_array_length(count)) as count from tbl1 group by id order by id;
结果:
id | count
----+-------
1 | 2
2 | 2
希望对你有帮助
我有一个tableorders
,它的结构是这样的:
create table orders (id serial primary key, created_at timestamp, updated_at timestamp, product_id varchar[]);
我为 product_id 我正在插入这样的数据:
insert into orders values (1,now(),now(),'{"1","2"}');
product_id
包含按特定订单订购的不同产品。每个 product_id
.
products
table 中都有一个条目
现在我想获取特定订单的 product_id
计数。
示例:对于我所做的上述插入,我应该得到如下内容:
Id Count
1 2
postgresql怎么可能?
编辑:抱歉弄乱了 create table
查询。这是一个 varchar[] 而不是 varchar(255)
您可以将值转换为数组并测量值的数量:
select o.*, cardinality(product_id)
from orders o
DDL:
CREATE TABLE tbl1 (id integer, count json);
INSERT INTO tbl1 (id, count) values (1, '["1", "2"]'::json), (2, '["3", "45"]');
查询:
SELECT id, sum(json_array_length(count)) as count from tbl1 group by id order by id;
结果:
id | count
----+-------
1 | 2
2 | 2
希望对你有帮助