SQLTeam.com | Weblogs | Forums

SQL temp tables syntax error

Hi, I've got to join 3 tables with aliases
I'm having trouble with the t5 onwards. The closing bracket should be the matching on to the select after FIRST FROM.. The t6 closing bracket should be the opening first select.

(SELECT *
FROM 

   (SELECT

            T1.company,
			ISNULL(T2.company_a,T1.company) as company_lookup,
			ISNULL(T3.user_count,0) as user_count,
			ISNULL(T4.user_count,0) as user_count_lookup
    FROM
			(SELECT * FROM	accounts) As T1

    LEFT JOIN
		    (SELECT * FROM	account_link) As T2
		     ON		T1.company = T2.company_b

LEFT JOIN
	      	(SELECT company, count(*) as user_count
	       	FROM	client
		    WHERE user_type = 2
			and	user_status != 7
		    group by company) As T3
		    on	T1.company = T3.company
	LEFT JOIN
	     	(SELECT company, count(*) as user_count
		    FROM	client
	    	 WHERE	user_type = 2
			and	user_status != 7
	    	group by company) As T4
	     	on	T2.company_a = t4.company)) As T5
    LEFT JOIN
	    (SELECT *  FROM	accounts)) As T6
    	ON	 T5.company = T6.company
        WHERE	(T5.user_count_lookup + T5.user_count) = 0
SELECT *
FROM 

   (SELECT

            T1.company,
			ISNULL(T2.company_a,T1.company) as company_lookup,
			ISNULL(T3.user_count,0) as user_count,
			ISNULL(T4.user_count,0) as user_count_lookup
    FROM
			(SELECT * FROM	accounts) As T1

    LEFT JOIN
		    (SELECT * FROM	account_link) As T2
		     ON		T1.company = T2.company_b

LEFT JOIN
	      	(SELECT company, count(*) as user_count
	       	FROM	client
		    WHERE user_type = 2
			and	user_status != 7
		    group by company) As T3
		    on	T1.company = T3.company
	LEFT JOIN
	     	(SELECT company, count(*) as user_count
		    FROM	client
	    	 WHERE	user_type = 2
			and	user_status != 7
	    	group by company) As T4
	     	on	T2.company_a = t4.company) As T5
    LEFT JOIN
	    (SELECT *  FROM	accounts) As T6
    	ON	 T5.company = T6.company
        WHERE	(T5.user_count_lookup + T5.user_count) = 0