gpt4 book ai didi

postgresql - Postgres - 是否可以按我的字段之一的子字符串进行分组?

转载 作者:行者123 更新时间:2023-11-29 11:59:49 24 4
gpt4 key购买 nike

这是我的 table :

 id                | integer                 | not null default nextval('frontend_prescription_id_seq'::regclass)
actual_cost | double precision | not null
chemical_id | character varying(9) | not null
practice_id | character varying(6) | not null

我想查询特定 practice_id 的结果,然后按日期和 前两个字符actual_cost 求和chemical_id。这在 Postgres 中可能吗?

换句话说,我希望输出看起来像这样:

processing_date   |    cost    |   chemical_id_substr
01-01-2010 1234 01
01-02-2010 4366 01
01-01-2010 3827 02
01-02-2010 8768 02

这是我当前的查询,但它按整个 chemical_id 分组,而不是子字符串:

    query = "SELECT SUM(actual_cost) as cost, processing_date, "
query += "chemical_id as id FROM frontend_items"
query += " WHERE practice_id=%s "
query += "GROUP BY processing_date, chemical_id"
cursor.execute(query, (practice_id,))

我不确定如何将其更改为按子字符串分组,或者我是否应该添加一个函数索引,或者我是否应该对我的表进行非规范化并添加一个新列。谢谢你的帮助。

最佳答案

你可以这样做,但你还需要确保选择列表中使用的是子字符串,而不是完整的列:

SELECT SUM(actual_cost) as cost, 
processing_date,
left(chemical_id,2) as id --<< use the same expression here as in the GROUP BY
FROM frontend_items
WHERE practice_id= %s
GROUP BY processing_date, left(chemical_id,2);

关于postgresql - Postgres - 是否可以按我的字段之一的子字符串进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29235581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com