简体   繁体   中英

Select single row or multiple rows based on condition

I'm trying to identify a student's home district by joining a student's zip code to a district zip code. A given district may overlap several zip codes, so several possible home districts may appear for the student. For example, Zip code 99999 may include the Houston and Sugarland school districts. I can narrow down the home district to a single record when the student's city has the same name as the district name as for example if the student's city is Houston and the district name is Houston. In that case, I only want to retrieve the Houston district, not both Houston and Sugarland. However, if the student happened to live in Bayou with the zip code of 99999, then I'd want to retrieve both Houston and Sugarland districts since I don't have a fix on the district. I've tried several approaches but cannot come up with a solution. Here's a primitive attempt:

Select S.Name, S.City, S.Zip, D.DistrictName
From tblStudent S
Left Join tblDistrict D on D.zip=S.zip
Where 
 (Case
     When D.DistrictName=S.City then D.DistrictName
     Else D.DistrictName
     End)=D.DistrictName

Any suggestions are greatly appreciated!

You can try selecting each case separately and then making a union of the two queries.

Case 1: District Name equals City Name

Case 2: There is no District Name that is equal to the City Name

Something like this:

Select S.Name, S.City, S.Zip, D.DistrictName
From tblStudent S
Inner Join tblDistrict D on D.zip=S.zip and D.DistrictName = S.City

Union

Select S.Name, S.City, S.Zip, D.DistrictName
From tblStudent S
Inner Join tblDistrict D on D.zip=S.zip
Where not exists (
  Select D2.* from tblDistrict D2
  Where D2.DistrictName = S.City
  And D2.zip = S.zip
)

SQL Fiddle: http://sqlfiddle.com/#!9/06d6d7/2/0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM