views:

82

answers:

1

Hi All,

I'm trying to work out a query that self join itself on a table using the eventnumber. I've never done a self join before.

What i'm trying to query is when a client has started off in a city which is chester to see what city they moved to. But I dont want to be able to see if they started off in another city. I would also like be only see the move once (So i'd only like to see if they went from chester to london rather then chester to london to wales)

The StartTimeDate is the same EndDateTime if they moved to another city.

Data example as follows if they started off in the city chester :-

 
clientid      EventNumber       City             StartDateTime                  EndDateTime
1                  1            Chester          10/03/2009               11/04/2010 13:00
1                  1            Liverpool        11/04/2010 13:00         30/06/2010 16:00 
1                  1            Wales            30/07/2010 16:00

the result I would like to see is on the 2nd row - so it only shows me liverpool.

Could anyone point in the right direcetion please?

+3  A: 

You can use aliases, which allow you to use two instances of the same table (replace MyTable with the name of your table):

SELECT A.clientid, A.EventNumber, B.City AS CityTo, A.EndDateTime AS MoveDateTime
  FROM MyTable A INNER JOIN MyTable B
       ON A.clientid = B.clientid
      AND A.EventNumber = B.EventNumber
      AND A.EndDateTime = B.StartDateTime
WHERE A.City = 'Chester'
Heinzi
This sql query is OK but you should add a where condition to filter the city you are looking for, otherwise it will return all the rows where people move form whatever city.That where condition should be with Table A
Claudia
@Claudia: Of course, thanks for the comment. WHERE clause added.
Heinzi
Works great thanks :)
If you like his answer you should 'accept' it.
egrunin