-- Gridded Galaxy Count
-- Find the gridded galaxy count (with the color cut)
-- In local tangent plane, ra/cos(dec) is a linear degree.
-- Assumes the existence of a Galaxy view of the Object table which
-- selects objects with sgSep > 0.5 (or whatever the approp. value is).

DECLARE @T TABLE(htmIDStart bigint, htmIDEnd bigint)
INSERT @T	
	SELECT * 
	FROM fHTMCoverRegion('CHULL J2000 175 -5 175 5 185 5 185 -5')

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 Galaxy as G CROSS JOIN @T T
WHERE htmID between T.HTMIDstart and T. HTMIDend
    and ra between 175 and 185 
    and dec between -5 and 5 
    and grColor > 1 
    and rMag < 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