Domanda

I'm thinking about a SQL query that returns me all entries from a column whose first 5 characters match. Any ideas? I'm thinking about entries where ANY first 5 characters match, not specific ones. E.g.

HelloA
HelloB
ThereC
ThereD
Something

would return the first four entries:

HelloA
HelloB
ThereC
ThereD

EDIT: I am using SQL92 so cannot use the left command!

È stato utile?

Soluzione

Try this :

SELECT *
FROM YourTable
WHERE LEFT(stringColumn, 5) IN (
    SELECT LEFT(stringColumn, 5)
    FROM YOURTABLE
    GROUP BY LEFT(stringColumn, 5)
    HAVING COUNT(*) > 1
    )

SQLFIDDLE DEMO

This selects the first 5 characters, groups by them and returns only the ones that happen more than once.

Or with Substring:

SELECT * FROM YourTable 
WHERE substring(stringColumn,1,5) IN (
  SELECT substring(stringColumn,1,5)
  FROM YOURTABLE
GROUP BY substring(stringColumn,1,5)
HAVING COUNT(*) > 1)
;

SQLFIDDLE DEMO

Altri suggerimenti

Sounds easy enough...

In SQL Server this would be something along the lines of

where Left(ColumnName,5) = '12345'

Try

Select *
From tbl t1
Where exists (
    Select 1
    From tbl t2
    Where left(t1.str, 5) = left(t2.str)
    Group by left(t2.str, 5)
    Having count(1) > 1
 )

You didn't specify your DBMS. If it supports Windowed Aggregate functions it's:

select *
from 
  (
    select
       tab.*, 
       count(*) over (partition by substring(col from 1 for 5) as cnt
    from tab
  ) as dt
where cnt > 1

You want to work with a CTE approach.

Something like this:

with CountriesCTE(Id, Name)
as (
select Id, Name from Countries
)
select distinct Countries.Name
from CountriesCTE, Countries
where left(CountriesCTE.Name,5) = left(Countries.Name,5) and CountriesCTE.Id <> Countries.Id
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top