tags:

views:

29

answers:

3
SELECT COUNT(SUBSTR(forenames,1,1))
FROM employee
WHERE
    (SUBSTR(forenames,1,1) like '%M%')
OR
    (SUBSTR(forenames,1,1) like '%A%')
+2  A: 
SELECT
   COUNT(forenames)
FROM
   employee
WHERE
   forenames like 'M%'
   OR forenames like 'A%'
Randolph Potter
Could also have used.... Where forenames like '[AM]%' Looks like you would get the same results and the same execution plan.
G Mastros
Nice one G. I also suggested a variation to APC's one below.
Randolph Potter
A: 

Straightforward count:

select count(*)
from   employee 
where  substr(forenames,1,1) in ('A', 'M') 
/

If you want to know number of each initial that would be :

select substr(forenames,1,1)
       , count(*)
from   employee 
where substr(forenames,1,1) in ('A', 'M') 
group by substr(forenames,1,1) 
/
APC
Also:select count(*)from employee where left(forenames,1) in ('A', 'M')
Randolph Potter
A: 

It's not clear to me what database this is for.
That said, this is a job for regex. Performing evaluations based on the results of a function performed on a column IE:

SUBSTR(forenames, 1, 1) LIKE '%M%'

...means that if an index exists on the column - the index can't be used even if the optimizer wanted to. Wildcarding the left side in a LIKE will also stop an index from being used.

MySQL


Use:

SELECT COUNT(*)
  FROM EMPLOYEE e
 WHERE e.forenames REGEXP '^[AM]'

Reference:

SQL Server


For SQL Server 2000, check this article regarding adding regex support. SQL Server 2005+, you have to enable CLR functions & write a CLR function that will allow you to execute regexes against column values.

SQL Server 2005+ example:

SELECT COUNT(*)
  FROM EMPLOYEE e
 WHERE dbo.RegexMatch(e.forenames, N'^[AM]') = 0

Oracle


Oracle 10g+ supports regular expressions - use the REGEXP_LIKE for this case:

SELECT COUNT(*)
  FROM EMPLOYEE e
 WHERE REGEXP_LIKE(e.forenames, '^[AM]')
OMG Ponies
Excellent Regex info website: http://www.regular-expressions.info/
OMG Ponies