我有一个表客户:
╔════════════╦═════╗
║ CustomerID ║ ... ║
╠════════════╬═════╣
║ ACC20011 ║ ... ║
║ ACC30122 ║ ... ║
║ ACC12356 ║ ... ║
║ EVG12345 ║ ... ║
║ DAA23445 ║ ... ║
║ DAA23548 ║ ... ║
╚════════════╩═════╝
我需要以下输出:
╔════════════╦═══════╗
║ CustomerID ║ Count ║
╠════════════╬═══════╣
║ Acc ║ 3 ║
║ EVG ║ 1 ║
║ DAA ║ 2 ║
╚════════════╩═══════╝
我写了以下查询。但我知道错了。请指正。
select CustomerID , count(*) as Count
from Customers
where CustomerID is like 'ACC%'
答案 0 :(得分:9)
尝试此查询:
SELECT SUBSTR(CustomerID, 1, 3) AS CustomerID, COUNT(*)
FROM Customers
GROUP BY SUBSTR(CustomerID, 1, 3)
答案 1 :(得分:2)
如果你有'A1234','ABCC2'
等数据格式
SELECT substr(CustomerID, 1, regexp_instr(CustomerID, '\d+') - 1) AS string
,count(*) as cnt
FROM customer
GROUP BY substr(CustomerID, 1, regexp_instr(CustomerID, '\d+') - 1)
修改强>
另外一种方法是使用regexp_replace
select regexp_replace(CustomerID,'\d+','') as string,count(*) cnt from customer
group by regexp_replace(CustomerID,'\d+','')
上面一个替换了customerid中的所有数字。