创建一个包含许多SUBSTR的选择COUNT

时间:2019-01-08 13:03:36

标签: sql

我正在尝试用SQL创建代码,该代码必须返回某些子字符串的出现次数。

我需要计算substrs重复的次数。

Ex:
Substring 'LQX' -> 10 times
Substring 'TES' -> 5 times

(select count(cod_ordem_producao) 
 from qt_qts.pla_ordem_producao
 where substr(cod_ordem_producao,1,3)='LQR') LQR,
(select count(cod_ordem_producao)
 from qt_qts.pla_ordem_producao
 where substr(cod_ordem_producao,1,3)='TES') TES
from Dual

如何在此代码中放置日期过滤器? (在日期之间)

Thx

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

select sum(case when cod_ordem_producao like 'LQR%' then 1 else 0 end) as lqr,
       sum(case when cod_ordem_producao like 'TES%' then 1 else 0 end) as tes
from qt_qts.pla_ordem_producao
where <whatever additional conditions you want>;

如果您通常想知道字符串的前三个字符是什么,可以使用group by

select substr(cod_ordem_producao, 1, 3) as first_three,
       count(*)
from qt_qts.pla_ordem_producao
where <whatever additional conditions you want>
group by substr(cod_ordem_producao, 1, 3);

这会将值放在单独的中,而不是放在单独的中。

答案 1 :(得分:0)

根据子字符串分组,然后过滤出日期

select substr(cod_ordem_producao,1,3) as substr_val
       ,count(cod_ordem_producao) 
  from qt_qts.pla_ordem_producao
 where substr(cod_ordem_producao,1,3) in ('LQR','TEST')
   and <date filter criteria>
group by substr(cod_ordem_producao,1,3)