选择SQL中带破折号的子字符串
我有一个名为选择SQL中带破折号的子字符串,sql,string,count,aggregate-functions,Sql,String,Count,Aggregate Functions,我有一个名为package\u 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 我需要计算包类型,但按包编号分组,即CYS01-01,CYS01-02 我所做的是: select substring(substring(package_type, '-', 3), '-', -2) as package_no,
package\u 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
我需要计算包类型
,但按包编号
分组,即CYS01-01
,CYS01-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
我得到这个错误:
整数的输入语法无效:“”
我预计结果如下:
package_no count
------------------
CYS01-01 2
CYS01-02 2
我该如何编写这个查询
谢谢。错误消息表明您正在运行Postgres。该数据库具有强大的字符串函数-您只需使用
split\u part()
:
注:
- 据推测,
属于类似于event\u date
的数据类型,因此应该将其与文字日期而不是字符串进行比较date
- 我怀疑状况
;进度=工程量清单
是否是表中的实际列?如果它是一个文本字符串,那么应该用单引号括起来bill\u of\u quantity
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);
毫无疑问,还有其他方法可以编写这样的查询。但是,字符串函数通常是特定于数据库的,您的问题没有指定您使用的数据库。您不能在GROUP BY子句中定义列别名。跳过此选项作为。。。您使用的是哪部分dbms?我删除了AS,still errorWong类型的argumenst:
子字符串(string,integer,integer)
编写查询时,请执行较小的步骤。当第一个子字符串工作时,添加第二个子字符串。然后添加分组等。
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);