Hi need help. The query below is pulling set zip that we need to analyze. The access standards is 2 in 10 miles.

I need to figure out a way to add in to this query Average dDstance to 1 Provider and Average Distance to 2 providers.

The person that wrote this code is no longer with the company, any help would be great. I am not that fluent with this type of coding.

Select zipcode,CityName, stateabbr as State, Count(distinct [PCS Number]) ProviderCount,Count(distinct case when distance < 10 then [PCS Number] else null end) Within10mileRadius---,---Distance

from

(

select distinct

ROUND(2 * ASIN(SQRT(POWER(SIN((( cast(z.Latitude as decimal(15,6)) / 180) * PI() - (CONVERT(Decimal(15,12),p.Latitude) / 180) * PI()) / 2) ,2)

+ COS(( cast(z.Latitude as decimal(15,6)) / 180) * PI()) * COS((CONVERT(Decimal(15,12),p.Latitude) / 180) * PI()) * POWER(SIN((( cast(z.Longitude as decimal(15,6)) / 180) * PI() - (CONVERT(Decimal(15,12), p.Longitude) / 180) * PI()) / 2), 2)))

* (6366.707019 * .621371), 4) as Distance

,z.zipcode,p.Latitude ,p.Longitude,[PCS Number]--,p.LastName ,p.FirstName

,z.CityName ,z.StateAbbr

from Vw_pfall p

left join uszipcodedata z on LEFT(p.zipCode,5) = z.ZIPCode

where p.SpecType = 'P' and CityType = 'D' --and p.ZipCode like '19406%'

and Z.zipcode in ('15042',

'15209',

'15314',

'15401',

'16630',

'16635',

'16648',

'17007',

'17011',

'17013',

'17015',

'17018',

'17019',

'17020',

'17022',

'17025',

'17033',

'17037',

'17038',

'17045',

'17046',

'17047',

'17050',

'17055',

'17057',

'17062',

'17065',

'17070',

'17078',

'17090',

'17093',

'17102',

'17103',

'17104',

'17109',

'17110',

'17111',

'17112',

'17113',

'17201',

'17241',

'17257',

'17266',

'17315',

'17319',

'17323',

'17324',

'17339',

'17365',

'17366',

'17370',

'17403',

'17404',

'17543',

'17603',

'18103',

'18250',

'18508',

'19072',

'19121' )

-----order by zipCode,Distance

)A

group by zipcode,CityName,StateAbbr----, Distance

-----select cast(z.Longitude as decimal(15,12)),Latitude,Longitude from uszipcodedata where ZIPCode = '19406'

------select latitude , cast(latitude as decimal(15,12)) from vw_pfall where zipcode like '19406%'

------ Select Distinct ZIPCode,CityName, StateAbbr

------ from uszipcodedata

------ WHERE CityType = 'D' and ZIPCode IN('17018',

------'17037',

------'17038',

------'17045',

------'17046',

------'17065',

------'17078',

------'17090',

------'17093',

------'17102',

------'17104',

------'17241',

------'17266',

------'17315',

------'17319',

------'17323',

------'17324',

------'17365',

------'17366',

------'17370',

------'18250',

------'19121')

------ order by ZIPCode