-- Find stars with multiple measurements with magnitude variations >0.1.     
-- Note that this runs very slowly unless explicit workarounds are included
-- for some SQLServer Optimizer bugs, which are NOT included here

SELECT S1.objID as objID1, S2.objID as ObjID2	-- select object IDs of star and its pair	
FROM   Star     as   S1,			-- the primary star
       photoObj  as   S2,			-- the second observation of the star
       neighbors as   N				-- the neighbor record
WHERE S1.objID = N.objID			-- insist the stars are neighbors
  and S2.objID = N.neighborObjID		-- using precomputed neighbors table
  and distance < 0.5/60			-- distance is 0.5 arc second or less
  and S1.run != S2.run				-- observations are two different runs
  and S2.type = dbo.fPhotoType('Star')		-- S2 is indeed a star
  and  S1.u between 1 and 27			-- S1 magnitudes are reasonable
  and  S1.g between 1 and 27
  and  S1.r between 1 and 27
  and  S1.i between 1 and 27
  and  S1.z between 1 and 27
  and  S2.u between 1 and 27		-- S2 magnitudes are reasonable.
  and  S2.g between 1 and 27
  and  S2.r between 1 and 27
  and  S2.i between 1 and 27
  and  S2.z between 1 and 27
  and (    	                       	-- and one of the colors is  different.
           abs(S1.u-S2.u) > .1 + (abs(S1.Err_u) + abs(S2.Err_u))  		
        or abs(S1.g-S2.g) > .1 + (abs(S1.Err_g) + abs(S2.Err_g)) 	
        or abs(S1.r-S2.r) > .1 + (abs(S1.Err_r) + abs(S2.Err_r)) 
        or abs(S1.i-S2.i) > .1 + (abs(S1.Err_i) + abs(S2.Err_i)) 
        or abs(S1.z-S2.z) > .1 + (abs(S1.Err_z) + abs(S2.Err_z)) 
	)
