Select SQL 中带破折号的子字符串

Select substring with dashes in SQL

我有一个名为 package_type 的专栏,它包含如下字符串:

TP-CYS01-01-2700-W-003
TP-CYS01-01-2700-W-004
TP-CYS01-02-2700-W-003
TP-CYS01-02-2700-W-001

我需要计算 package_type 但按 package_no 分组,即 CYS01-01CYS01-02.

我做的是这样的:

select 
    substring(substring(package_type, '-', 3), '-', -2) as package_no,
    count(distinct package_type)
from
    project_june 
where 
    progress = bill_of_quantity and event_date = '2020-06-12'
group by 
    substring(substring(package_type, '-', 3), '-', -2) as package_no

我收到这个错误:

Invalid input syntax for integer: "-"

我希望结果是这样的:

package_no   count
------------------
CYS01-01      2
CYS01-02      2

我该如何编写此查询?

谢谢。

错误消息表明您是运行 Postgres。该数据库具有强大的字符串函数 - 你可以只使用 split_part():

select split_part(package_no, '-', 2) as package_no, count(distinct package_type) as cnt
from project_june 
where progress = bill_of_quantity and event_date = date '2020-06-12'
group by split_part(package_no, '-', 2)

备注:

  • 据推测,event_date 是类似于 date 的数据类型,因此应该将其与文字日期而不是字符串进行比较。

  • 我对病情持怀疑态度progress = bill_of_quantitybill_of_quantity 是您 table 中的实际列吗?如果它是一个文字字符串,那么它应该用单引号括起来

您的字符串似乎具有固定格式 -- 并且您希望从第 4 个位置开始有 8 个字符。这表明您可以使用:

select substring(package_type, 4, 8), as package_no,
       count(distinct package_type)
from project_june 
where progress = bill_of_quantity and
      event_date = '2020-06-12'
group by substring(package_type, 4, 8);

毫无疑问,还有其他方法可以编写这样的查询。但是,字符串函数通常是特定于数据库的,您的问题没有指定您使用的是什么数据库。