-- Gridded galaxy counts and masks. Actually consists of TWO queries.
-- Create a gridded count of galaxies with u-g>1 and r<21.5 over
-- 60<declination<70, and 200<right ascension<210, 
-- on a grid, and create a map of masks over the same grid.  
-- Scan the table for galaxies and group them in cells 2 arc-minutes
-- on a side. Provide predicates for the color restrictions on u-g 
-- and r and to limit the search to the portion of the sky defined 
-- by the right ascension and declination conditions.  
-- Return the count of qualifying galaxies in each cell. 
-- Run another query with the same grouping, but with a predicate 
-- to include only objects such as satellites, planets, and airplanes 
-- that obscure the cell.  The second query returns a list of cell 
-- coordinates that serve as a mask for the first query.

--- First find the gridded galaxy count (with the color cut)
--- In local tangent plane, ra/cos(dec) is a linear degree.

SELECT cast((ra/cos(cast(dec*30 as int)/30.0))*30 as int)/30.0 as raCosDec, 
       cast(dec*30 as int)/30.0                                as dec, 
       count(*)                                                as pop
into mydb.sampletest
FROM   Galaxy as G, 
       fHTM_Cover('CONVEX J2000 6 175 -5 175 5 185 5 185 -5') as T
WHERE  htmID  between T.HTMIDstart* power(2,28)and T. HTMIDend*power(2,28)
  and  ra between 175 and 185
  and  dec between -5 and 5
  and  u-g > 1
  and  r < 21.5
group by  cast((ra/cos(cast(dec*30 as int)/30.0))*30 as int)/30.0, 
          cast(dec*30 as int)/30.0    

-- now build mask grid.
-- This is a separate query if no temp tables can be made
SELECT 	cast((ra/cos(cast(dec*30 as int)/30.0))*30 as int)/30.0 as raCosDec, 
	cast(dec*30 as int)/30.0                                as dec, 
	count(*)                                                as pop
FROM    photoObj as PO, 
	dbo.fHTM_Cover('CONVEX J2000 6 175 -5 175 5 185 5 185 -5') as T,
	PhotoType as PT
WHERE  htmID between T. HTMIDstart*power(2,28) and T. HTMIDend*power(2,28)
  and  ra between 175 and 185
  and  dec between -5 and 5
  and PO.type = PT.value
  and PT.name in ('COSMIC_RAY', 'DEFECT', 'GHOST', 'TRAIL', 'UNKNOWN')
group by  cast((ra/cos(cast(dec*30 as int)/30.0))*30 as int)/30.0, 
          cast(dec*30 as int)/30.0    
