I have a table called TempAllAddresses
with the following columns - ID
, Address
, State
. I want to populate a new table with Address
, State
, and Count
. Count
should represent how many records there are in the TempAllAddresses table that have an address like this address followed by a wildcard. If that made no sense, here's an example to illustrate -
Let's say I have a record like this:
ID Address State
12345 13 Phoenix NY
What I want to do is insert a new record into a new table called AddressCount
that has 13 Phoenix for the Address
, NY for the State
, and the number of records in the table that have NY as the State and an address LIKE '13 Phoenix%' for the Count
.
I want to accomplish this with an inner join of TempAllAddresses on itself. This is what I've tried, but it doesn't seem to accomplish what I'm looking for:
SELECT t1.Address, t1.State, COUNT(t2.address) As NumEntities
FROM TempAllAddresses t1
INNER JOIN TempAllAddresses t2
ON t1.state = t2.state
AND T2.Address LIKE t1.address + '%'
GROUP BY t1.State, t1.Address
The Count is definitely off, though. It should be equivalent to running "SELECT COUNT(*) FROM TempAllAddresses WHERE State=thisRecordsState and Address LIKE thisRecordsAddress + '%'
". How can I accomplish this? What am I doing wrong?
Edit:
The count seems to be off in the following way - If I have a record like I mentioned above, and then I have 2 other records that also have a state of NY, and then have addresses of "13 Phoenix Road" and "13 Phoenix Rd", then I want to get in my final table a record like this:
13 Phoenix NY 3
Instead, I seem to be getting:
13 Phoenix NY 9
I'm not quite sure what's happening here... some sort of cartesian product? Permutations...? Can anyone explain this?
Edit 2: A further edit since I seem to be misunderstood (and really need a solution :( )... Here is a query with a correlated subselect that accomplishes what I'm looking for. I'd like to do the same thing with an inner join of the table on itself rather than a subselect.
SELECT Address, State,
(SELECT Count(*)
FROM TempAllAddresses innerQry
WHERE innerQry.address LIKE outerQry.address + '%'
AND innerQry.state = outerQry.state) As NumEntities
FROM TempAllAddresses outerQry
Basically, for each record, I want to get the number of records in the table that have the same state and an address that begins with this address (or is equal to... I do want to include this address as part of the count).