<?PHP
/*
 * DIREITOS AUTORAIS RESERVADOS (C) 2007 UFRJ
 * 
 * ESTE PROGRAMA É SOFTWARE LIVRE; VOCÊ PODE REDISTRIBUÍ-LO E/OU MODIFICÁ-LO SOB OS
 * TERMOS DA LICENÇA PÚBLICA GERAL GNU CONFORME PUBLICADA PELA FREE SOFTWARE FOUNDATION;
 * TANTO A VERSÃO 2 DA LICENÇA, COMO (A SEU CRITÉRIO) QUALQUER VERSÃO POSTERIOR.

 * ESTE PROGRAMA É DISTRIBUÍDO NA EXPECTATIVA DE QUE SEJA ÚTIL, PORÉM, SEM NENHUMA GARANTIA;
 * NEM MESMO A GARANTIA IMPLÍCITA DE COMERCIABILIDADE OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA.
 * CONSULTE A LICENÇA PÚBLICA GERAL DO GNU PARA MAIS DETALHES.
 * 
 * VOCÊ DEVE TER RECEBIDO UMA CÓPIA DA LICENÇA PÚBLICA GERAL DO GNU JUNTO COM ESTE PROGRAMA; 
 * SE NÃO, ACESSE <<HTTP://WWW.GNU.ORG/LICENSES/LICENSES.PT-BR.HTML>>
 */

<?
//GUSTAVO HACK
session_start();
//$_SESSION['logon_semed']=1;
//$_SESSION['f_numerocreas']=1;
session_commit();

include "includes/config.php";
include "includes/begin.php";

/* INCLUI PROCEDIMENTO AJAX */
include "includes/ajax.php";

error_reporting(0);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CREAS - CENTRO DE REFERÊNCIA ESPECIAL DA ASSISTÊNCIA SOCIAL</title>
<link href="stylo.css" rel="stylesheet" type="text/css" />
<?
include "includes/config3.php";

//filtro
$s_CREAS = trim(strtoupper($_POST["s_CREAS"]));
$s_situacao = $_POST["s_situacao"];
$s_dtini = $_POST["s_dtini"];
$s_dtfim = $_POST["s_dtfim"];

$filtro_CREAS = "";

if ( $s_CREAS != "")
{
      $filtro_CREAS = " AND numerocreas = '" . $s_CREAS . "'";
}

if ($s_situacao != "")
{
   $filtro_CREAS = $filtro_CREAS . " AND numerocreas || cast(datacadastrousuario as varchar) in ( select numerocreas || cast(datacadastrousuario as varchar) from pcni_assistenciacreas.usuariosituacao where situacao = '" . $s_situacao . "' ) ";
}

//data INI
if ($s_dtini != '')
{
   $data_1 =  substr($s_dtini,6,4);
   $data_2 =  substr($s_dtini,2,3);
   $data_3 = "/". substr($s_dtini,0,2);
   $s_dtini_aux = "'" . $data_1 . $data_2 . $data_3 . " 00:00:00'";

   $filtro_CREAS = $filtro_CREAS." and numerocreas || cast(datacadastrousuario as varchar) in ( select numerocreas || cast(datacadastrousuario as varchar) from visita v where v.datavisita  >= ".$s_dtini_aux." ) ";
}

//data FIM
if ($s_dtfim != '')
{
   $data_1 =  substr($s_dtfim,6,4);
   $data_2 =  substr($s_dtfim,2,3);
   $data_3 = "/". substr($s_dtfim,0,2);
   $s_dtfim_aux = "'" . $data_1 . $data_2 . $data_3 . " 23:59:59'";

   $filtro_CREAS = $filtro_CREAS." and numerocreas || cast(datacadastrousuario as varchar) in ( select numerocreas || cast(datacadastrousuario as varchar) from visita v where v.datavisita  <= ".$s_dtfim_aux." ) ";
}



//numero total de respostas efetuadas
$sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.usuario where 1=1 #CREAS";
$sql = str_replace("#CREAS",$filtro_CREAS,$sql);
$result=pg_query($dbh, $sql);

$row = pg_fetch_array($result);
$qt_tot = $row["qt"];


//numero total de visitas
$sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.visita where 1=1 #CREAS";
$sql = str_replace("#CREAS",$filtro_CREAS,$sql);
$result=pg_query($dbh, $sql);

$row = pg_fetch_array($result);
$qt_tot_visita = $row["qt"];


function ObtemValor($resposta, $result, &$perc_calc, $tot)
{
 $i = 0;
 $perc_calc = 0;
 $qt_tot = $tot;
 while ($row = pg_fetch_array($result,$i))
 {
 	if( trim($row["resposta"]) == trim($resposta) )
        {
                if ($qt_tot > 0)
                {
        		$perc_calc = round($row["qt"] / $qt_tot,4) * 100;
                }
        	return $row["qt"];
        }
        $i++;
 }
 return 0;
}


?>

<script language="javascript">

function LTrim ( parTexto )
{
    return parTexto.replace( /^\s*/, "" );
}

function RTrim ( parTexto )
{
    return parTexto.replace( /\s*$/, "" );
}

function Trim ( parTexto )
{
    return RTrim(LTrim(parTexto));
}

function ValidaDataAux( pData )
{
    var dt;
    var i, j;
    var sChar;
    var fc_dia, fc_mes, fc_ano;


    pData = Trim(pData);

    if (pData.length == 0) return false;

    // Separa a string em dia, mÃªs e ano
    i = pData.indexOf("/");
    if (i <= 0)  return false;
    j = pData.indexOf("/", i+1);
    if (j == -1) return false;
    fc_dia = pData.substring(0, i);
    fc_mes = pData.substring(i+1, j);
    fc_ano = pData.substring(j+1, pData.length);

    // Verifica nÃºmero de dÃ­gitos
    if (fc_dia.length != 2)  return false;
    if (fc_mes.length != 2)  return false;
    if (fc_ano.length != 4)  return false;

    // Verifica se hÃ¡ apenas caracteres vÃ¡lidos (nÃºmeros)
    dt = fc_dia + fc_mes + fc_ano;
    for (i = 0; i < dt.length; i++)
    {
        sChar = dt.charAt(i);
        if (sChar < "0" || sChar > "9") return false;
    }

    // Verifica se sÃ£o nÃºmeros vÃ¡lidos
    if (fc_mes < 1 || fc_mes > 12)  return(false);
    if (fc_dia < 1 || fc_dia > 31)  return(false);
    if (fc_ano < 1)  return(false);
    if (fc_mes == 4 || fc_mes == 6 || fc_mes == 9 || fc_mes == 11)
    {
        if (fc_dia == 31)  return(false);
        if (fc_ano < 1753) return(false);
    }

    if (fc_mes == 2)
    {
        fc_a1 = parseInt(fc_ano/4);
        if (isNaN(fc_a1)) { return(false) };
        if (fc_dia > 29) return(false);
        if (fc_dia == 29 && ((fc_ano/4) != parseInt(fc_ano/4))) return(false);
    }

    return(true);
}

function ValidaData(obj)
{
   if (obj.value == '')
   {
       return false;
   }

   if (!ValidaDataAux(obj.value))
   {
       alert('Data incorreta.');
       setTimeout("document.getElementById('" + obj.id + "').focus();",1);
       return false;
   }
   return true;
}

</script>

</head>

<body topmargin="0" leftmargin="0">

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><? include "includes/config2.php"; ?></td>
  </tr>
  <tr>
    <td class="titulos"><div align="center" class="titulos2">
      <p>.:: ESTATÍSTICAS  ::.<br />
        Secretaria Municipal de Assistência Social<br />
          Prefeitura da Cidade de Nova Iguaçu<br />
          <br />
            <span class="mago"><br />
          </span></p>
      </div></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>
      <form name="InclusaoMatricula" action="#" method="POST" enctype="application/x-www-form-urlencoded" >
        <table width="800" border="0" align="center" cellpadding="1" cellspacing="0" bgcolor="#EFEFEF">

        <tr>
            <td colspan="4"><div align="left">CREAS: <select name="s_CREAS" class="campos2">
            <option value="">Todos</option>
             <?
                        $sql3 = "SELECT * FROM CREAS ORDER BY NOMEFANTASIACREAS ";
                	$result2=pg_query($dbh, $sql3);

                         while ($row2 = pg_fetch_array($result2))
			 {      $selected = "";

                         	if  (trim($row2["numerocreas"]) == trim($s_CREAS))
                                {
                                   $selected = " selected";
                                }
                          	echo "<option value=\"". $row2["numerocreas"] ."\" ". $selected . ">". trim($row2["nomefantasiacreas"]) ."</option>";
                         }
             ?>
            </select>
            &nbsp;
            Situação:
             <select name="s_situacao" class="campos2" id="s_situacao">
                <option value="">Todas</option>
		<option value="A" <? if ($s_situacao == 'A') echo ' selected'; ?>>VALIDADO</option>
                <option value="N" <? if ($s_situacao == 'N') echo ' selected'; ?>>SEM VALIDAÇÃO</option>
                <option value="I" <? if ($s_situacao == 'I') echo ' selected'; ?>>NÃO VALIDADO</option>
                </select>

             Últ. Visita entre:
                <input name="s_dtini" type="text" class="campos2" id="s_dtini" size="10" maxlength="10" onkeypress="mascara(this,data);" value="<? echo $s_dtini;?>" onblur="ValidaData(this);"/>
                e
                <input name="s_dtfim" type="text" class="campos2" id="s_dtfim" size="10" maxlength="10" onkeypress="mascara(this,data);" value="<? echo $s_dtfim;?>" onblur="ValidaData(this);"/>

             <input type="submit" value="Filtrar" class="botao2"/></div></td>
            </tr>
          <tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          <tr>
            <td colspan="4"><div align="center" class="titulos3">Frequências Simples por Pergunta<br></div></td>
            </tr>
          <tr>

          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

           <tr>
            <td colspan="4">1.  Tem cônjuge/companheiro que mora no domicílio?
            <?
              $sql = "SELECT case when conjugemoradomiciliousuario = 'S' then 'Sim'
		when conjugemoradomiciliousuario = 'N' then 'Não'
		when conjugemoradomiciliousuario = 'X' then 'Não Sabe/Não Respondeu'
		else 'Não se Aplica' end as resposta, count(*) as qt  ,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By conjugemoradomiciliousuario order by 3 desc";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);

              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
             <?
              $qt = 0;
              while ($row = pg_fetch_array($result))
		 {
                 	$qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>

              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">2. Número de cômodos do domicilio:
             <?
              $sql = "SELECT numcomodosdomiciliousuario as resposta, count(*) as qt,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By numcomodosdomiciliousuario order by 3 desc";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;

             	while ($row = pg_fetch_array($result,$i))
		 {
                  	$qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>

          <tr>
            <td colspan="4">3. Situações diagnosticadas pela equipe interdisplinar:
            <br>


             <?
              $sql = "SELECT d.nomediagnostico as resposta, count(*) as qt ,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuariodiagnostico where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuariodiagnostico vd inner join pcni_assistenciacreas.diagnostico d on d.diagnostico = vd.diagnostico where 1=1 #CREAS
              Group By d.nomediagnostico order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result,$i))
		 {
                    $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>

           <tr>
            <td colspan="4">4. Alguém no seu domicílio recebe, mensalmente, algum desses benefícios do governo: ( respostas múltiplas- todos os campos devem ser percorridos):
            <br>
            <?
              $sql = "SELECT nomebeneficio as resposta,
                        (select count(*) from pcni_assistenciacreas.usuariobeneficio u where u.beneficio = b.beneficio and u.respostabeneficio = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.usuariobeneficio u where u.beneficio = b.beneficio and u.respostabeneficio = 'N' #CREAS) as qt_nao,
			(select count(*) from pcni_assistenciacreas.usuariobeneficio u where u.beneficio = b.beneficio and u.respostabeneficio = 'X' #CREAS) as qt_nao_sabe
			from pcni_assistenciacreas.beneficio b order by nomebeneficio";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <table width="70%" border="1">
              <tr>
              	<td align="center" rowspan="2"><b>Benefício</b></td>
                <td align="center" colspan="3"><b>Qtde.</b></td>
                <td align="center" colspan="3"><b>%</b></td>
                <!--<td align="center" colspan="2"><b>Totais</b></td>-->
              </tr>
              <tr>

                <td align="center"><b>Sim</b></td>
                <td align="center"><b>Não</b></td>
                <td align="center"><b>Não sabe/<br>Não respondeu</b></td>
                <td align="center"><b>Sim</b></td>
                <td align="center"><b>Não</b></td>
                <td align="center"><b>Não sabe/<br>Não respondeu</b></td>
                <!--<td align="center"><b>Total</b></td>
                <td align="center"><b>%</b></td>-->
              </tr>

               <?
                $qt_sim = 0;
                $qt_nao = 0;
                $qt_nao_sabe = 0;
             	while ($row = pg_fetch_array($result))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? $qt_sim = $qt_sim + $row["qt_sim"]; echo $row["qt_sim"];  ?></td>
                <td align="right"><? $qt_nao = $qt_nao + $row["qt_nao"]; echo $row["qt_nao"];  ?></td>
                <td align="right"><? $qt_nao_sabe = $qt_nao_sabe + $row["qt_nao_sabe"]; echo $row["qt_nao_sabe"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_sim"] / $qt_tot)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao"] / $qt_tot)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao_sabe"] / $qt_tot)*100,2,',','.'); ?></td>
                <!--<td align="right"><? echo $row["qt_nao_sabe"] + $row["qt_sim"] + $row["qt_nao"];  ?></td>
                <td align="right"><? echo number_format((($row["qt_nao_sabe"] + $row["qt_sim"] + $row["qt_nao"]) / $qt_tot)*100,2,',','.'); ?></td>-->
	        </tr>
                 <?
		 }

                 $tot_geral = $qt_sim + $qt_nao + $qt_nao_sabe;
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo number_format($qt_sim,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_nao,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_nao_sabe,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_sim/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao_sabe/$tot_geral)*100,2,',','.');?></b></td>
                <!--<td align="right"><b><? echo number_format($qt_nao_sabe + $qt_sim + $qt_nao,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format((($qt_nao_sabe + $qt_sim + $qt_nao)/$tot_geral)*100,2,',','.');?></b></td>-->
              </tr>
               <?
              $sql = "SELECT count(*) as qt
			From pcni_assistenciacreas.usuario u
			Where 1=1 #CREAS and Not exists ( select 1 from  pcni_assistenciacreas.usuariobeneficio b where u.numerocreas = b.numerocreas and u.datacadastrousuario = b.datacadastrousuario
			and respostabeneficio <> 'X' )";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $row = pg_fetch_array($result)

            ?>
               <tr>
              	<td colspan="9"><b>No. de Questionários com 100% Não Sabe/Não Respondeu = <? echo $row["qt"]; ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">5. Você ou alguém do seu domicílio RECEBE apoio de parentes, amigos que não moram com vocês ou outras instituições? (por exemplo, dinheiro, visitas, compra de alimentos ou bens ou outra forma de ajuda) (Resposta Múltipla)
             <?

              //numero total de apoios recebidos
	       /*	$sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.usuarioapoio where 1=1 #CREAS";
                $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
                $result=pg_query($dbh, $sql);

		$row = pg_fetch_array($result);
		$qt_tot_apoio = $row["qt"];*/

              $sql = "SELECT d.nomeapoio as resposta, count(*) as qt ,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuarioapoio where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuarioapoio vd inner join pcni_assistenciacreas.apoio d on d.apoio = vd.apoio where 1=1 #CREAS
              Group By d.nomeapoio order by 3 desc  ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;               
              

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;

             	while ($row = pg_fetch_array($result))
		 {
                     $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">6. Que tipo de apoio é recebido principalmente? (Resposta Múltipla)
            <br>


               <?

              //numero total de apoios recebidos
               /*	$sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.usuariotipoapoio where 1=1 #CREAS";
                $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
                $result=pg_query($dbh, $sql);

		$row = pg_fetch_array($result);
		$qt_tot_apoio = $row["qt"];*/

              $sql = "SELECT d.nometipoapoio as resposta, count(*) as qt,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuariotipoapoio where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuariotipoapoio vd inner join pcni_assistenciacreas.tipoapoio d on d.tipoapoio = vd.tipoapoio
              where 1=1 #CREAS Group By d.nometipoapoio
              order by 3 desc";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;


            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                   $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


           <tr>
            <td colspan="4">7. Quando você precisa resolver um problema sério a quem você recorre em primeiro lugar?
            <br>


               <?

              $sql = "SELECT d.nomerecorre as resposta, count(*) as qt,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario vd inner join pcni_assistenciacreas.recorre d on d.recorre = vd.recorreusuario
              where 1=1 #CREAS Group By d.nomerecorre order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">8. Há caso de gravidez precoce no seu domicílio atualmente?
             <?
              $sql = "SELECT case when gravidezprecocedomicusuario = 'S' then 'Sim'
		when gravidezprecocedomicusuario = 'N' then 'Não'
		when gravidezprecocedomicusuario = 'X' then 'Não Sabe/Não Respondeu'
		else 'Não se Aplica' end  as resposta, count(*) as qt ,
               (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario where 1=1 #CREAS
              Group By gravidezprecocedomicusuario order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

              <br> Gravidez Precoce por Faixa Etária:
              <?

              //numero total de gravidez precoce
               /*	$sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.usuario where faixagravidezprecocedomicusuario > '0' #CREAS ";
                $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
                $result=pg_query($dbh, $sql);

		$row = pg_fetch_array($result);
		$qt_tot_gravidez = $row["qt"];*/

              $sql = "SELECT case when faixagravidezprecocedomicusuario = '1' then '10-14 anos' else '15-18 anos' end  as resposta, count(*) as qt,
               (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where  faixagravidezprecocedomicusuario > '0' #CREAS) as float)) as perc
               FROM pcni_assistenciacreas.usuario where faixagravidezprecocedomicusuario > '0' #CREAS
               Group By faixagravidezprecocedomicusuario order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
              ?>
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>
            <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
           <tr>
            <td colspan="4">9. Alguma criança (até 14 anos) no seu domicílio trabalha?
             <?
              $sql = "SELECT case when criancadomictrabusuario = 'S' then 'Sim'
		when criancadomictrabusuario = 'N' then 'Não'
		when criancadomictrabusuario = 'X' then 'Não Sabe/Não Respondeu'
		else 'Não se Aplica' end  as resposta, count(*) as qt,
                 (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
               FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By criancadomictrabusuario order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
           <tr>
            <td colspan="4">10. Algum adolescente no seu domicílio cumpre, ou já cumpriu, uma medida sócio-educativa em regime de Privação de Liberdade ou já esteve internada no DEGASE?
             <?
              $sql = "SELECT case when medidasocioeducativausuario = 'A' then 'Cumpre atualmente'
		when medidasocioeducativausuario = 'J' then 'Já cumpriu'
		when medidasocioeducativausuario = 'N' then 'Nunca Cumpriu'
                when medidasocioeducativausuario = 'X' then 'Não sabe/Não Respondeu'
		else 'Não se Aplica' end  as resposta, count(*) as qt,
              (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario where 1=1 #CREAS
              Group By medidasocioeducativausuario order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
              <br> Medida Sócio-Educativa em cumprimento:
              <?

              $sql = "SELECT descricao  as resposta,
		       ( select count(*) from  pcni_assistenciacreas.usuario u where u.codigomedidasocioeducativa = m.codigo and u.medidasocioeducativausuario = 'A' #CREAS ) as qt,
	               ((select count(*) from  pcni_assistenciacreas.usuario u where  u.codigomedidasocioeducativa = m.codigo and u.medidasocioeducativausuario = 'A' #CREAS  )/greatest(cast((select count(*) from pcni_assistenciacreas.usuario u where  codigomedidasocioeducativa is not null and u.medidasocioeducativausuario = 'A' #CREAS ) as float),1)) as perc
			FROM pcni_assistenciacreas.medidasocioeducativa m
			order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);

              $result=pg_query($dbh, $sql);
              $perc = 0;
              ?>
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>


              <br> Medida Sócio-Educativa já cumprida:
              <?

              $sql = "SELECT descricao  as resposta,
		       ( select count(*) from  pcni_assistenciacreas.usuario u where u.codigomedidasocioeducativa = m.codigo and u.medidasocioeducativausuario = 'J' #CREAS ) as qt,
	               ((select count(*) from  pcni_assistenciacreas.usuario u where  u.codigomedidasocioeducativa = m.codigo and u.medidasocioeducativausuario = 'J' #CREAS  )/greatest(cast((select count(*) from pcni_assistenciacreas.usuario u where  codigomedidasocioeducativa is not null and u.medidasocioeducativausuario = 'J' #CREAS ) as float),1)) as perc
			FROM pcni_assistenciacreas.medidasocioeducativa m
			order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);

              $result=pg_query($dbh, $sql);
              $perc = 0;
              ?>
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
           <tr>
            <td colspan="4">11. Alguma criança ou adolescente no seu domicílio freqüenta ou já freqüentou algum abrigo? (Nota: A partir da consulta do nome do abrigo e de seu endereço o atendente deverá indicar se o abrigo é da Prefeitura ou particular)
            <?
              $sql = "SELECT case when frequentaabrigocriancausuario = 'A' then 'Freqüenta atualmente'
		when frequentaabrigocriancausuario = 'J' then 'Já freqüentou'
		when frequentaabrigocriancausuario = 'N' then 'Nunca freqüentou'
                when frequentaabrigocriancausuario = 'X' then 'Não sabe/Não Respondeu'
		else 'Não se Aplica' end   as resposta, count(*) as qt ,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
              FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By frequentaabrigocriancausuario
              order by 3 desc ";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>

          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
           <tr>
            <td colspan="4">12. Algum idoso no seu domicílio freqüenta ou já freqüentou algum abrigo? (Nota: A partir da consulta do nome do abrigo e de seu endereço o atendente deverá indicar se o abrigo é da Prefeitura ou particular)
            <?
              $sql = "SELECT case when frequentaabrigoidosousuario = 'A' then 'Freqüenta atualmente'
		when frequentaabrigoidosousuario = 'J' then 'Já freqüentou'
		when frequentaabrigoidosousuario = 'N' then 'Nunca freqüentou'
                when frequentaabrigoidosousuario = 'X' then 'Não sabe/Não Respondeu'
		else 'Não se Aplica' end  as resposta, count(*) as qt,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
                 FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By frequentaabrigoidosousuario order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>

          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
           <tr>
            <td colspan="4">13. Alguma criança ou adolescente no seu domicílio está sendo acompanhado pelo conselho Tutelar ou já foi acompanhado?
            <?
              $sql = "SELECT case when acompconselhotutelarusuario = 'A' then 'Em acompanhamento'
		when acompconselhotutelarusuario = 'J' then 'Já esteve'
		when acompconselhotutelarusuario = 'N' then 'Nunca esteve'
                when acompconselhotutelarusuario = 'X' then 'Não sabe/Não Respondeu'
		else 'Não se Aplica' end  as resposta, count(*) as qt,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
                FROM pcni_assistenciacreas.usuario where 1=1 #CREAS Group By acompconselhotutelarusuario order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
             	while ($row = pg_fetch_array($result))
		 {
                  $qt += $row["qt"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">14. Quais serviços/ equipamentos as pessoas que moram no seu domicílio utilizam no seu bairro (bairro onde mora)- respostas múltiplas?
            <br>
            <?
              $sql = "SELECT nomeservicosequipamentos as resposta, (select count(*) from pcni_assistenciacreas.usuarioservicosequipamentos u where u.servicosequipamentos = b.servicosequipamentos and u.respostaservicosequipamentos = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.usuarioservicosequipamentos u where u.servicosequipamentos = b.servicosequipamentos and u.respostaservicosequipamentos = 'N' #CREAS) as qt_nao,
			(select count(*) from pcni_assistenciacreas.usuarioservicosequipamentos u where u.servicosequipamentos = b.servicosequipamentos and u.respostaservicosequipamentos = 'X' #CREAS) as qt_nao_sabe
			from pcni_assistenciacreas.servicosequipamentos b order by nomeservicosequipamentos";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <table width="70%" border="1">
             <tr>
              	<td align="center" rowspan="2"><b>Serviço</b></td>
                <td align="center" colspan="3"><b>Qtde.</b></td>
                <td align="center" colspan="3"><b>%</b></td>
              </tr>
              <tr>

                <td align="center"><b>Sim</b></td>
                <td align="center"><b>Não</b></td>
                <td align="center"><b>Não sabe/<br>Não respondeu</b></td>
                <td align="center"><b>Sim</b></td>
                <td align="center"><b>Não</b></td>
                <td align="center"><b>Não sabe/<br>Não respondeu</b></td>
              </tr>

               <?
                $qt_sim = 0;
                $qt_nao = 0;
                $qt_nao_sabe = 0;
             	while ($row = pg_fetch_array($result))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? $qt_sim = $qt_sim + $row["qt_sim"]; echo $row["qt_sim"];  ?></td>
                <td align="right"><? $qt_nao = $qt_nao + $row["qt_nao"]; echo $row["qt_nao"];  ?></td>
                <td align="right"><? $qt_nao_sabe = $qt_nao_sabe + $row["qt_nao_sabe"]; echo $row["qt_nao_sabe"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_sim"] / $qt_tot)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao"] / $qt_tot)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao_sabe"] / $qt_tot)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }

                 $tot_geral = $qt_sim + $qt_nao + $qt_nao_sabe;
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo number_format($qt_sim,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_nao,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_nao_sabe,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_sim/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao_sabe/$tot_geral)*100,2,',','.');?></b></td>
              </tr>
               <?
              $sql = "SELECT count(*) as qt
				From pcni_assistenciacreas.usuario u
				Where 1=1 #CREAS and Not exists ( select 1 from  pcni_assistenciacreas.usuarioservicosequipamentos b where u.numerocreas = b.numerocreas and u.datacadastrousuario = b.datacadastrousuario
				and respostaservicosequipamentos <> 'X' )";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $row = pg_fetch_array($result);

            ?>
               <tr>
              	<td colspan="9"><b>No. de Questionários com 100% Não Sabe/Não Respondeu = <? echo $row["qt"]; ?></b></td>
              </tr>
              </table>
            </td>
          </tr>
          
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
           <tr>
            <td colspan="4">15. Grau de Parentesco da Pessoa da família que procurou o CREAS:
            <?
              $sql = " SELECT p.descricaograuparentesco as resposta, count(*) as qt ,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.visita where 1=1 #CREAS) as float)) as perc
                FROM pcni_assistenciacreas.visita v 
                Inner join pcni_assistenciacreas.familia f on v.tipopessoafamiliaprocuroucreas = f.tipopessoafamilia 
                And v.numtipopessoafamiliaprocuroucreas = f.numtipopessoafamilia and v.numerocreas = f.numerocreas and v.datacadastrousuario = f.datacadastrousuario
                Inner join pcni_assistenciacreas.parentescocreas p on p.grauparentesco = f.grauparentesco
                where 1=1 #CREAS
                Group By p.descricaograuparentesco order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
                  <td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
                 while ($row = pg_fetch_array($result))
         {
                  $qt += $row["qt"];
                 ?>

                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
            </tr>
                 <?
         }
              ?>
              <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
          

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          
          <tr>
           <tr>
            <td colspan="4">16. Programa(s) em que o usuário se insere:
            <?
              $sql = " SELECT p.nomeprograma as resposta, count(*) as qt ,
                    (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma where 1=1 #CREAS) as float)) as perc
                    FROM pcni_assistenciacreas.visitaprograma v 
                    Inner join pcni_assistenciacreas.programa p on p.programa = v.programa
                    where 1=1  #CREAS
                    Group By p.nomeprograma order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
                  <td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
                 while ($row = pg_fetch_array($result))
         {
                  $qt += $row["qt"];
                 ?>

                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
            </tr>
                 <?
         }
              ?>
              <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
              
              <?
              $sql = " SELECT * from
                    pcni_assistenciacreas.programa 
                     order by nomeprograma ";
              
              $result_aux=pg_query($dbh, $sql);
              
              while ($row_aux = pg_fetch_array($result_aux))
              {
                echo "<br><br><b>" . $row_aux["nomeprograma"] . "</b>";
                $programa = $row_aux["programa"];
                
                //numero total de visitas por programa
                $sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.visitaprograma where programa = $programa #CREAS";
                $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
                $result=pg_query($dbh, $sql);

                $row = pg_fetch_array($result);
                $qt_tot_visita_pgm = $row["qt"];
                
                
                //numero total de visitas por programa
                $sql = "SELECT count(*) as qt FROM pcni_assistenciacreas.visitaprograma v inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas 
                        and u.datacadastrousuario = v.datacadastrousuario where programa = $programa  and sexousuario = 'F' #CREAS";
                
                $aux = str_replace("numerocreas","u.numerocreas",$filtro_CREAS);
                $sql = str_replace("#CREAS",$aux,$sql);
                
                $result=pg_query($dbh, $sql);

                $row = pg_fetch_array($result);
                $qt_tot_f = $row["qt"];
                
                $qt_tot_m = $qt_tot_visita_pgm - $qt_tot_f;
                
                
                $sql = "Select '-1 ano' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) < 1 and v.programa = $programa and u.sexousuario = 'M' #CREAS) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) < 1 and v.programa = $programa and u.sexousuario = 'F' #CREAS) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) < 1  #CREAS Group by 1

                        union

                        Select '1 a 5' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 1 and 5 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 1 and 5 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 1 and 5  #CREAS Group by 1

                        union

                        Select '6 a 10' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 6 and 10 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 6 and 10 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 6 and 10  #CREAS Group by 1


                        union

                        Select '11 a 14' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 11 and 14 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 11 and 14 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 11 and 14  #CREAS Group by 1


                        union

                        Select '15 a 19' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 15 and 19 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 15 and 19 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 15 and 19  #CREAS Group by 1


                        union

                        Select '20 a 29' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 20 and 29 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 20 and 29 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 20 and 29  #CREAS Group by 1


                        union

                        Select '30 a 59' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 30 and 59 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) between 30 and 59 and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) between 30 and 59  #CREAS Group by 1


                        union

                        Select '60+' as resposta, 1 as ordem,
                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) >= 60 and v.programa = $programa and u.sexousuario = 'M' #CREAS ) as qt_m,

                        (select count(*) From pcni_assistenciacreas.visitaprograma v 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v.numerocreas and u.datacadastrousuario = v.datacadastrousuario
                        where extract(year from age(datanascimentousuario)) >= 60and v.programa = $programa and u.sexousuario = 'F' #CREAS ) as qt_f,

                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitaprograma u where u.programa = $programa  #CREAS ) as float)) as perc    

                        From pcni_assistenciacreas.visitaprograma v2 
                        Inner join pcni_assistenciacreas.usuario u on u.numerocreas = v2.numerocreas and u.datacadastrousuario = v2.datacadastrousuario and v2.programa = $programa 
                        Where  extract(year from age(u.datanascimentousuario)) >= 60  #CREAS Group by 1

                        order by 5 desc";
                        
                        $aux = str_replace("numerocreas","u.numerocreas",$filtro_CREAS);
                        $sql = str_replace("#CREAS",$aux,$sql);
                        
                        //echo $sql;
                        //exit;
                        $result=pg_query($dbh, $sql);
                ?>
                  <table width="50%" border="1">
               <tr>
                  <td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>%</b></td>
              </tr>
              <tr>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_m = 0;
               $qt_f = 0;
                 while ($row = pg_fetch_array($result,$i))
                 {
                             $qt_m = $qt_m + $row["qt_m"];
                                $qt_f = $qt_f + $row["qt_f"];
                         ?>

                         <tr>
                          <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                        <td align="right"><? echo $row["qt_m"];  ?></td>
                        <td align="right"><? echo $row["qt_f"];  ?></td>
                        <td align="right"><? echo $row["qt_f"] + $row["qt_m"];  ?></td>
                        <td align="right"><? echo number_format(($row["qt_m"] / $qt_tot_visita_pgm)*100,2,',','.'); ?></td>
                        <td align="right"><? echo number_format(($row["qt_f"] / $qt_tot_visita_pgm)*100,2,',','.'); ?></td>
                        <td align="right"><? echo number_format(($row["perc"]) *100,2,',','.'); ?></td>
                    </tr>
                         <?
                 }
                      ?>
                      <tr>
                          <td><b>Totais</b></td>
                        <td align="right"><b><? echo $qt_m; ?></b></td>
                        <td align="right"><b><? echo $qt_f; ?></b></td>
                        <td align="right"><b><? echo $qt_f + $qt_m; ?></b></td>
                        <td align="right"><b><? echo number_format(($qt_m / $qt_tot_visita_pgm)*100,2,',','.'); ?></b></td>
                        <td align="right"><b><? echo number_format(($qt_f / $qt_tot_visita_pgm)*100,2,',','.'); ?></b></td>
                        <td align="right"><b><? echo number_format((($qt_f + $qt_m) / $qt_tot_visita_pgm)*100,2,',','.'); ?></b></td>
                      </tr>
                      </table>
                
                <?
                     
              }

            ?>
              
              
              </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
          

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          
          
          <tr>
           <tr>
            <td colspan="4">17. O usuário foi encaminhado ao CREAS por:
            <?
              $sql = " SELECT p.nomeencaminhadopor as resposta, count(*) as qt ,
                    (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuarioencaminhadopor where 1=1 #CREAS) as float)) as perc
                    FROM pcni_assistenciacreas.usuarioencaminhadopor v 
                    Inner join pcni_assistenciacreas.encaminhadopor p on p.encaminhadopor = v.encaminhadopor
                    where 1=1     #CREAS
                    Group By p.nomeencaminhadopor order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
                  <td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
                 while ($row = pg_fetch_array($result))
         {
                  $qt += $row["qt"];
                 ?>

                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
            </tr>
                 <?
         }
              ?>
              <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
          

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          
          
          <tr>
            <td colspan="4">18. Inscrição em Programas do CREAS:
            <br>
            <?
              $sql = "SELECT nomeprograma as resposta, (select count(*) from pcni_assistenciacreas.visitainscricao i where i.programa = p.programa and i.situacaoinscricao = 'A' #CREAS) as qt_ativo,
                (select count(*) from pcni_assistenciacreas.visitainscricao i where i.programa = p.programa and i.situacaoinscricao = 'D' #CREAS) as qt_desligado,
                (select count(*) from pcni_assistenciacreas.visitainscricao i where i.programa = p.programa and i.situacaoinscricao = 'AB' #CREAS) as qt_abandono,
                (select count(*) from pcni_assistenciacreas.visitainscricao i where i.programa = p.programa and i.situacaoinscricao = 'DE' #CREAS) as qt_encaminhado,
                (select count(*) from pcni_assistenciacreas.visitainscricao i where programa in (1,2) #CREAS) as qt_tot_inscricao
                from pcni_assistenciacreas.programa p where programa in (1,2) order by nomeprograma";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <table width="70%" border="1">
             <tr>
                  <td align="center" rowspan="2"><b>Programa</b></td>
                <td align="center" colspan="5"><b>Qtde.</b></td>
                <td align="center" colspan="5"><b>%</b></td>
              </tr>
              <tr>

                <td align="center"><b>Ativo</b></td>
                <td align="center"><b>Desligado</b></td>
                <td align="center"><b>Abandono</b></td>
                <td align="center"><b>Encaminhado</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Ativo</b></td>
                <td align="center"><b>Desligado</b></td>
                <td align="center"><b>Abandono</b></td>
                <td align="center"><b>Encaminhado</b></td>
                <td align="center"><b>Total</b></td>
              </tr>

               <?
                $qt_ativo = 0;
                $qt_desligado = 0;
                $qt_abandono = 0;
                $qt_encaminhado = 0;
                
                 while ($row = pg_fetch_array($result))
         {

                 ?> 
                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? $qt_ativo = $qt_ativo + $row["qt_ativo"]; echo $row["qt_ativo"];  ?></td>
                <td align="right"><? $qt_desligado = $qt_desligado + $row["qt_desligado"]; echo $row["qt_desligado"];  ?></td>
                <td align="right"><? $qt_abandono = $qt_abandono + $row["qt_abandono"]; echo $row["qt_abandono"];  ?></td>
                <td align="right"><? $qt_encaminhado = $qt_encaminhado + $row["qt_encaminhado"]; echo $row["qt_encaminhado"];  ?></td>
                <td align="right"><b><? echo $row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"];  ?></b></td>
                <td align="right"><? echo number_format(($row["qt_ativo"] /   ($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"]) )*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_desligado"] / ($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"]))*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_abandono"] / ($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"]))*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_encaminhado"] / ($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"]))*100,2,',','.'); ?></td>
                <td align="right"><b><? echo number_format((($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"])/($row["qt_ativo"] + $row["qt_desligado"] + $row["qt_abandono"] + $row["qt_encaminhado"]))*100,2,',','.');  ?></b></td>
            </tr>
                 <?
         }

                 $tot_geral = $qt_ativo + $qt_desligado + $qt_abandono + $qt_encaminhado;
              ?>

            <!--  <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo number_format($qt_ativo,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_desligado,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_abandono,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format($qt_encaminhado,0,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_ativo/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_desligado/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_abandono/$tot_geral)*100,2,',','.');?></b></td>
                <td align="right"><b><? echo number_format(($qt_encaminhado/$tot_geral)*100,2,',','.');?></b></td>
              </tr>             -->
              </table>
            </td>
          </tr>
          
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          
          
          <tr>
           <tr>
            <td colspan="4">19. Tipo de Atendimento Prestado ao Usuário pelo CREAS:
            <?
              $sql = " SELECT p.nometipoatendimento as resposta, count(*) as qt ,
                    (Count(*)/cast((select count(*) from pcni_assistenciacreas.visitatipoatendimento where 1=1 #CREAS) as float)) as perc
                    FROM pcni_assistenciacreas.visitatipoatendimento v 
                    Inner join pcni_assistenciacreas.tipoatendimento p on p.tipoatendimento = v.tipoatendimento
                    where 1=1    #CREAS
                    Group By p.nometipoatendimento order by 3 desc ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
                  <td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
                 while ($row = pg_fetch_array($result))
         {
                  $qt += $row["qt"];
                 ?>

                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
            </tr>
                 <?
         }
              ?>
              <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
          

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          
          
          
          <tr>
           <tr>
            <td colspan="4">20.  Tipo de Acompanhamento social e interdisciplinar:
            <?
              $sql = " SELECT p.nomeacompanhamento as resposta, count(*) as qt ,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuarioacompanhamento where 1=1 #CREAS) as float)) as perc
                FROM pcni_assistenciacreas.usuarioacompanhamento v 
                Inner join pcni_assistenciacreas.acompanhamento p on p.acompanhamento = v.acompanhamento 
                where 1=1    #CREAS
                Group By p.nomeacompanhamento 
                
                order by 3 desc ";
                
                /*
                 union
                SELECT p2.nomeacompanhamento as resposta, count(*) as qt ,
                (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuarioacompanhamento where 1=1 #CREAS) as float)) as perc
                FROM pcni_assistenciacreas.usuarioacompanhamento v 
                Inner join pcni_assistenciacreas.acompanhamento p on p.acompanhamento = v.acompanhamento 
                Inner join pcni_assistenciacreas.acompanhamento p2 on p2.acompanhamento = p.acompanhamentopai 
                where 1=1    #CREAS
                Group By p2.nomeacompanhamento 
                */
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;
            ?>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <table width="50%" border="1">
              <tr>
                  <td align="center"><b>Resposta</b></td>
                <td align="center"><b>Quantidade</b></td>
                <td align="center"><b>%</b></td>
              </tr>
              <?
                $qt = 0;
                 while ($row = pg_fetch_array($result))
         {
                  $qt += $row["qt"];
                 ?>

                 <tr>
                  <td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
            </tr>
                 <?
         }
              ?>
              <tr>
                  <td><b>Totais</b></td>
                <td align="right"><b><? echo $qt; ?></b></td>
                <td align="right"><b><? echo number_format(($qt/$qt)*100,2,',','.'); ?></b></td>
              </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
          

          <tr>
            <td height="10" colspan="4"></td>
            </tr>
          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>
          


          <tr>
            <td colspan="4"><div align="center">
              <input name="voltar" type="button" class="botao" id="voltar" value="voltar" onclick="window.location='main2.php?acao=voltar';"/>
              </div>
            </td>
            </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4"><div align="center" class="titulos3">Para a Pessoa de Referência<br></div></td>
            </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
           </tr>


          <tr>
            <td colspan="4">1. Cruzamento Sexo x Idade

             <?

              $sql = "Select count(*)  as qt From pcni_assistenciacreas.usuario Where sexousuario = 'F' #CREAS ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);

	      $row = pg_fetch_array($result);
	      $qt_tot_f = $row["qt"];

              $qt_tot_m = $qt_tot - $qt_tot_f;

              $sql = "select '0 a 5' as resposta, 1 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 0 and 5 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 0 and 5 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 0 and 5 #CREAS group by 1
			union
                        select '6 a 10' as resposta, 1 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 6 and 10 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 6 and 10 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 6 and 10 #CREAS group by 1
			union
                        select '11 a 14' as resposta, 1 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 11 and 14 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 11 and 14 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 11 and 14 #CREAS group by 1
			union
			select '15 a 19' as resposta, 2 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 15 and 19 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 15 and 19 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 15 and 19 #CREAS group by 1
			union
			select '20 a 29' as resposta, 3 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 20 and 29 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 20 and 29 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 20 and 29 #CREAS group by 1
			union
			select '30 a 59' as resposta, 4 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 30 and 59 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  between 30 and 59 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  between 30 and 59 #CREAS group by 1

			union
			select '60+' as resposta, 5 as ordem,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  >= 60 and u2.sexousuario = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.usuario u2 where extract(year from age(datanascimentousuario))  >= 60 and u2.sexousuario = 'F' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario u
			where  extract(year from age(datanascimentousuario))  >= 60 #CREAS group by 1
			order by 5 desc";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
               <tr>
              	<td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>%</b></td>
              </tr>
              <tr>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_m = 0;
               $qt_f = 0;
             	while ($row = pg_fetch_array($result,$i))
		 {
                 	$qt_m = $qt_m + $row["qt_m"];
                        $qt_f = $qt_f + $row["qt_f"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_m"];  ?></td>
                <td align="right"><? echo $row["qt_f"];  ?></td>
                <td align="right"><? echo $row["qt_f"] + $row["qt_m"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_m"] / $qt_tot_m)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_f"] / $qt_tot_f)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"]) *100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_m; ?></b></td>
                <td align="right"><b><? echo $qt_f; ?></b></td>
                <td align="right"><b><? echo $qt_f + $qt_m; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_m / $qt_tot_m)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_f / $qt_tot_f)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_f + $qt_m) / $qt_tot)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">2. Naturais do Município de Nova Iguaçu

             <?
              $sql = "Select 'NOVA IGUAÇU' as resposta, count(*) as qt
			from pcni_assistenciacreas.usuario u
			left outer join pcni_assistenciacreas.municipio m on m.codigomunicipio = u.codigomunicipiousuario
			where codigomunicipio = '3303500'  #CREAS
			union
			Select 'OUTROS'  as resposta, count(*) as qt
			From pcni_assistenciacreas.usuario u
			where (u.codigomunicipiousuario <> '3303500' or codigomunicipiousuario  is null) #CREAS ";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Município</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">3. Distribuição do total de documentos apresentados por tipo

             <?

              $sql = "Select 'NIS' as resposta, 1 as ordem, count(*) as qt,
	               (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where nisusuario is not null #CREAS
			union
			Select 'CPF' as resposta, 2 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where cpfusuario is not null #CREAS
			union
			Select 'RG' as resposta, 3 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where rgusuario is not null  #CREAS
			union
			Select 'CARTEIRA DE TRABALHO' as resposta, 4 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where carteiratrabusuario is not null #CREAS
			union
			Select 'TÍTULO DE ELEITOR' as resposta, 5 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where titeleitorusuario is not null #CREAS

			union
			Select 'PIS/PASEP' as resposta, 6 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where pispasepusuario is not null #CREAS

			union
			Select 'CERTIDÃO CIVIL' as resposta, 7 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where certidaotipousuario is not null  #CREAS

			union
			Select 'CARTEIRA DE MOTORISTA' as resposta, 8 as ordem, count(*) as qt,
                        (Count(*)/(
                       cast((select count(*) from pcni_assistenciacreas.usuario where nisusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cpfusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where rgusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where carteiratrabusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where titeleitorusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where pispasepusuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where certidaotipousuario is not null #CREAS) as float)
                       + cast((select count(*) from pcni_assistenciacreas.usuario where cartmotoristausuario is not null #CREAS) as float)
                       )) as perc
			from pcni_assistenciacreas.usuario
			where cartmotoristausuario is not null #CREAS

			order by 4 desc";



              	//numero total de docs
              	$sql_ext = " select sum(qt) as qt_doc from ( " . $sql . ") as X ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

		$row = pg_fetch_array($result);
		$qt_tot_doc = $row["qt_doc"];

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Documento</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot_doc)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_doc; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_doc/$qt_tot_doc)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">4. Pessoas sem documentação

             <?

              $sql = " select 'SIM' as resposta, 1, count(*) as qt,
              		 (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario
			where semdocumentosusuario  = 'S'  #CREAS
			UNION
			select 'NÃO' as resposta, 2,count(*) as qt,
                         (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario
			where (semdocumentosusuario  = 'N' or semdocumentosusuario  is null) #CREAS order by 3 desc";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Sem Documento?</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">5. Imóveis cadastrados e não cadastrados

             <?

              $sql = " select 'SIM' as resposta, 1, count(*) as qt,
              		 (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where logradouronaocadastradousuario in ('N', 'S') #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario
			where logradouronaocadastradousuario  = 'N' #CREAS
			UNION
			select 'NÃO' as resposta, 2, count(*) as qt,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where logradouronaocadastradousuario in ('N', 'S') #CREAS) as float)) as perc
			from pcni_assistenciacreas.usuario
			where logradouronaocadastradousuario  = 'S' #CREAS order by 4 desc";

              //numero total de docs
              	$sql_ext = " select sum(qt) as qt_cad from ( " . $sql . ") as X ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

		$row = pg_fetch_array($result);
		$qt_tot_cad = $row["qt_cad"];

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Imóvel Cadastrado?</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_cad; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_cad/$qt_tot_cad)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>


           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">6. Endereços fora do município

             <?

              $sql = " Select 'SIM' as resposta, 1, count(*) as qt
			from pcni_assistenciacreas.usuario
			where logradourotipojustificativa  = '1' #CREAS
			UNION
			Select 'NÃO' as resposta, 2, count(*) as qt
			from pcni_assistenciacreas.usuario
			where logradourotipojustificativa  = '2' #CREAS order by 3 desc";

              //numero total de docs
              	$sql_ext = " select sum(qt) as qt_aux from ( " . $sql . ") as X ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

		$row = pg_fetch_array($result);
		$qt_tot_cad = $row["qt_aux"];

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Endereços fora do município?</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot_cad)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_cad; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_cad/$qt_tot_cad)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>


            <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">7. Distribuição do total de endereços não fixos

             <?

              $sql = " Select coalesce(nometipoendereco, 'Possui Endereço Fixo') as resposta, count(*) as qt
			From pcni_assistenciacreas.usuario u
			left outer join pcni_assistenciacreas.tipoendereco t on t.tipoendereco = u.tipoendereco  where 1=1 #CREAS
			group by nometipoendereco order by 2 desc";

              //numero total
              	$sql_ext = " select sum(qt) as qt_aux from ( " . $sql . ") as X ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

		$row = pg_fetch_array($result);
		$qt_tot_cad = $row["qt_aux"];

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Tipo de Endereço</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result,$i))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot_cad)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_cad; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_cad/$qt_tot_cad)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4"><div align="center">
              <input name="voltar" type="button" class="botao" id="voltar" value="voltar" onclick="window.location='main2.php?acao=voltar';"/>
              </div>
            </td>
            </tr>

             <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4"><div align="center" class="titulos3">Para a Família<br></div></td>
            </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">1. Cruzamento Sexo x Idade

             <?

              //numero total
              	$sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null #CREAS ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_fam = $row["qt"];

                $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where sexopessoafamilia in ('M') and idadepessoafamilia is not null #CREAS ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_m = $row["qt"];

		$qt_tot_f =  $qt_tot_fam - $qt_tot_m;

              $sql = "   select '-1 ano' as resposta, 0 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where  u2.sexopessoafamilia = 'M' and tipoidade = 'M' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where  u2.sexopessoafamilia = 'F' and tipoidade = 'M' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  tipoidade = 'M'  #CREAS group by 1
                        union
                         select '0 a 5' as resposta, 1 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 0 and 5 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 0 and 5 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 0 and 5 and tipoidade = 'A'  #CREAS group by 1
			union
			select '6 a 10' as resposta, 2 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 6 and 10 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 6 and 10 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 6 and 10 and tipoidade = 'A'  #CREAS group by 1
			union
			select '11 a 14' as resposta, 3 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 11 and 14 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 11 and 14 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 11 and 14 and tipoidade = 'A'  #CREAS group by 1
			union
			select '15 a 19' as resposta, 4 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 15 and 19 and tipoidade = 'A'  #CREAS group by 1
			union
			select '20 a 29' as resposta, 5 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 20 and 29 and tipoidade = 'A'  #CREAS group by 1
			union
			select '30 a 59' as resposta, 6 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 30 and 59 and tipoidade = 'A'  #CREAS group by 1
			union
			select '60+' as resposta, 7 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.sexopessoafamilia = 'M' and tipoidade = 'A' #CREAS) as qt_m,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.sexopessoafamilia = 'F' and tipoidade = 'A' #CREAS) as qt_f,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') and idadepessoafamilia is not null  #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  >= 60 and tipoidade = 'A'  #CREAS group by 1
			order by 5 desc";
              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
               <tr>
              	<td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_m = 0;
               $qt_f = 0;
             	while ($row = pg_fetch_array($result,$i))
		 {
                 	$qt_m = $qt_m + $row["qt_m"];
                        $qt_f = $qt_f + $row["qt_f"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_m"];  ?></td>
                <td align="right"><? echo $row["qt_f"];  ?></td>
                <td align="right"><? echo $row["qt_f"] +  $row["qt_m"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_m"] / $qt_tot_m)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_f"] / $qt_tot_f)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_m; ?></b></td>
                <td align="right"><b><? echo $qt_f; ?></b></td>
                <td align="right"><b><? echo $qt_f + $qt_m; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_m / $qt_tot_m)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_f / $qt_tot_f)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_f + $qt_m)/ $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>

              <tr>
              	<td colspan="1"><b>Núm. Médio por Família</b></td>
                <td colspan="6" align="center"><b><? echo number_format((($qt_f + $qt_m)/ $qt_tot),2,',','.'); ?></b></td>
              </tr>

              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">2. Cor/Raça

             <?

              $sql = "Select coalesce(descricaocorraca, 'Não Informada') as resposta,  count(*) as qt
			from pcni_assistenciacreas.familia u
			left outer join pcni_assistenciacreas.corracausuario c on c.corraca = u.corracamembrofamilia
                        where 1=1 #CREAS
			group by descricaocorraca
			order by 2 desc";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Cor/Raça</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>
               <?
             	while ($row = pg_fetch_array($result))
		 {

                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot_fam)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_fam; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_fam/$qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">3. Cruzamento Freqüência escolar x Idade

             <?

             	$sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia <= 14 #CREAS";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_fam = $row["qt"];


                $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia <= 14 and frequentaescolamembrofamilia = 'S' #CREAS";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_sim = $row["qt"];


		$qt_tot_nao = $qt_tot_fam - $qt_tot_sim;

                            $sql = "select '0 a 5' as resposta, 1 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where (idadepessoafamilia  between 0 and 5 or tipoidade = 'M') and frequentaescolamembrofamilia = 'S' #CREAS) as qt_frequenta,
			(select count(*) from pcni_assistenciacreas.familia u2 where (idadepessoafamilia  between 0 and 5 or tipoidade = 'M') and (frequentaescolamembrofamilia = 'N' or frequentaescolamembrofamilia is null) #CREAS) as qt_nao_frequenta,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and (idadepessoafamilia <= 14 or tipoidade = 'M') #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  ((idadepessoafamilia  between 0 and 5  and tipoidade = 'A') or  (tipoidade = 'M')) #CREAS group by 1

                        union

			select '6 a 10' as resposta, 2 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 6 and 10 and frequentaescolamembrofamilia = 'S' and tipoidade = 'A' #CREAS) as qt_frequenta,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 6 and 10 and tipoidade = 'A' and (frequentaescolamembrofamilia = 'N' or frequentaescolamembrofamilia is null) #CREAS) as qt_nao_frequenta,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and (idadepessoafamilia <= 14 or tipoidade = 'M') #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 6 and 10 and tipoidade = 'A'  #CREAS group by 1

                        union

                        select '11 a 14' as resposta, 3 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 11 and 14 and frequentaescolamembrofamilia = 'S' and tipoidade = 'A' #CREAS) as qt_frequenta,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 11 and 14 and tipoidade = 'A' and (frequentaescolamembrofamilia = 'N' or frequentaescolamembrofamilia is null) #CREAS) as qt_nao_frequenta,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and (idadepessoafamilia <= 14 or tipoidade = 'M') #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 11 and 14 and tipoidade = 'A' #CREAS group by 1
			order by 5 desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
              <tr>
              	<td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Frequenta</b></td>
                <td align="center"><b>Não Frequenta</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Frequenta</b></td>
                <td align="center"><b>Não Frequenta</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_frequenta = 0;
               $qt_nao_frequenta = 0;
             	while ($row = pg_fetch_array($result,$i))
		 {
                 	$qt_frequenta = $qt_frequenta + $row["qt_frequenta"];
                        $qt_nao_frequenta = $qt_nao_frequenta + $row["qt_nao_frequenta"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_frequenta"];  ?></td>
                <td align="right"><? echo $row["qt_nao_frequenta"];  ?></td>
                <td align="right"><? echo $row["qt_nao_frequenta"] + $row["qt_frequenta"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_frequenta"] / $qt_tot_sim)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao_frequenta"] / $qt_tot_nao)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"]  )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_frequenta; ?></b></td>
                <td align="right"><b><? echo $qt_nao_frequenta; ?></b></td>
                <td align="right"><b><? echo $qt_nao_frequenta + $qt_frequenta; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_frequenta / $qt_tot_sim)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao_frequenta / $qt_tot_nao)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_nao_frequenta + $qt_frequenta) / $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">4. Cruzamento Alfabetizado x Idade

             <?

                $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 #CREAS ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_fam = $row["qt"];

                $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 and alfabetizadomembrofamilia = 'S' #CREAS ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_sim = $row["qt"];

                $qt_tot_nao = $qt_tot_fam - $qt_tot_sim;

                            $sql = "
			select '15 a 19' as resposta, 4 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and alfabetizadomembrofamilia = 'S' #CREAS) as qt_alfabetizado,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and (alfabetizadomembrofamilia = 'N' or alfabetizadomembrofamilia is null) #CREAS) as qt_nao_alfabetizado,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 15 and 19  #CREAS group by 1
			union
			select '20 a 29' as resposta, 5 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and alfabetizadomembrofamilia = 'S' #CREAS) as qt_alfabetizado,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and (alfabetizadomembrofamilia = 'N' or alfabetizadomembrofamilia is null) #CREAS) as qt_nao_alfabetizado,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 20 and 29  #CREAS group by 1
			union
			select '30 a 59' as resposta, 6 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and alfabetizadomembrofamilia = 'S' #CREAS) as qt_alfabetizado,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and (alfabetizadomembrofamilia = 'N' or alfabetizadomembrofamilia is null) #CREAS) as qt_nao_alfabetizado,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 30 and 59  #CREAS group by 1
			union
			select '60+' as resposta, 7 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >=60 and alfabetizadomembrofamilia = 'S' #CREAS) as qt_alfabetizado,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >=60  and (alfabetizadomembrofamilia = 'N' or alfabetizadomembrofamilia is null) #CREAS) as qt_nao_alfabetizado,
                        (Count(*)/cast((Select count(*) as qt from pcni_assistenciacreas.familia Where idadepessoafamilia is not null and idadepessoafamilia > 14 #CREAS) as float)) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  >= 60 #CREAS group by 1
			order by 5 desc";

                        $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
                	$result=pg_query($dbh, $sql);
        	      $perc = 0;

            ?>
            <br>
            <table width="50%" border="1">
            <tr>
              	<td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Alfabetizado</b></td>
                <td align="center"><b>Não Alfabetizado</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Alfabetizado</b></td>
                <td align="center"><b>Não Alfabetizado</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_frequenta = 0;
               $qt_nao_frequenta = 0;
             	while ($row = pg_fetch_array($result,$i))
		 {
                 	$qt_alfabetizado = $qt_alfabetizado + $row["qt_alfabetizado"];
                        $qt_nao_alfabetizado = $qt_nao_alfabetizado + $row["qt_nao_alfabetizado"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_alfabetizado"];  ?></td>
                <td align="right"><? echo $row["qt_nao_alfabetizado"];  ?></td>
                <td align="right"><? echo $row["qt_nao_alfabetizado"] + $row["qt_alfabetizado"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_alfabetizado"] / $qt_tot_sim)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao_alfabetizado"] / $qt_tot_nao)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_alfabetizado; ?></b></td>
                <td align="right"><b><? echo $qt_nao_alfabetizado; ?></b></td>
                <td align="right"><b><? echo $qt_nao_alfabetizado + $qt_alfabetizado; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_alfabetizado / $qt_tot_sim)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao_alfabetizado / $qt_tot_nao)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_nao_alfabetizado + $qt_alfabetizado) / $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">5. Cruzamento Ocupação x Idade

             <?

                            $sql = "Select o.nomeocupacao as resposta, 1,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.ocupacao = o.ocupacao #CREAS)   as qt_16_19,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.ocupacao = o.ocupacao #CREAS)   as qt_20_29,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.ocupacao = o.ocupacao #CREAS)   as qt_30_59,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.ocupacao = o.ocupacao #CREAS)   as qt_60,

                                (( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.ocupacao = o.ocupacao #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.ocupacao = o.ocupacao #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.ocupacao = o.ocupacao #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.ocupacao = o.ocupacao #CREAS)) / ". $qt_tot_fam  .".00 as perc
				From pcni_assistenciacreas.ocupacao o
				union
				Select 'Ocupação Não Informada' as resposta, 2,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.ocupacao is null #CREAS)   as qt_16_19,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.ocupacao is null #CREAS)   as qt_20_29,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.ocupacao is null #CREAS)   as qt_30_59,
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.ocupacao is null #CREAS)   as qt_60,

                                (( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.ocupacao is null #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.ocupacao is null #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.ocupacao is null #CREAS)   +
				( Select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.ocupacao is null #CREAS)) / ". $qt_tot_fam  .".00 as perc
				From pcni_assistenciacreas.ocupacao where ocupacao = 1
				Order by 6 desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="70%" border="1">
            <tr>
              	<td align="center" rowspan="2"><b>Ocupação</b></td>
                <td align="center" colspan="5"><b>Quantidade</b></td>
                <td align="center" colspan="5"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>15 a 19</b></td>
                <td align="center"><b>20 a 29</b></td>
                <td align="center"><b>30 a 59</b></td>
                <td align="center"><b>60+</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>15 a 19</b></td>
                <td align="center"><b>20 a 29</b></td>
                <td align="center"><b>30 a 59</b></td>
                <td align="center"><b>60+</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_16_19 = 0;
               $qt_20_29 = 0;
               $qt_30_59 = 0;
               $qt_60 = 0;



               while ($row = pg_fetch_array($result))
		 {
	               $qt_16_19 = $qt_16_19  + $row["qt_16_19"];
	               $qt_20_29 = $qt_20_29 + $row["qt_20_29"];
	               $qt_30_59 = $qt_30_59 + $row["qt_30_59"];
	               $qt_60 = $qt_60 + $row["qt_60"];
                 }
                 
                $qt_tot_geral = $qt_16_19 + $qt_20_29 + $qt_30_59 + $qt_60;

                pg_result_seek($result, 0);
             	while ($row = pg_fetch_array($result))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_16_19"];  ?></td>
                <td align="right"><? echo $row["qt_20_29"];  ?></td>
                <td align="right"><? echo $row["qt_30_59"];  ?></td>
                <td align="right"><? echo $row["qt_60"];  ?></td>
                <td align="right"><? echo $row["qt_16_19"] + $row["qt_20_29"] + $row["qt_30_59"] + $row["qt_60"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_16_19"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_20_29"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_30_59"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_60"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_16_19; ?></b></td>
                <td align="right"><b><? echo $qt_20_29; ?></b></td>
                <td align="right"><b><? echo $qt_30_59; ?></b></td>
                <td align="right"><b><? echo $qt_60; ?></b></td>
                <td align="right"><b><? echo $qt_16_19 + $qt_20_29 + $qt_30_59 + $qt_60 ; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_16_19 / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_20_29 / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_30_59 / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_60 / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_16_19 + $qt_20_29 + $qt_30_59 + $qt_60 ) / $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>

          <tr>
            <td colspan="4">6. Ocupação x Sexo

             <?

             	$sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia Where sexopessoafamilia in ('M','F')  #CREAS ";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
		$result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_fam = $row["qt"];

              $sql = "Select o.nomeocupacao as resposta, 1,
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'M' and u2.ocupacao = o.ocupacao #CREAS)   as qt_m,
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'F' and u2.ocupacao = o.ocupacao #CREAS)   as qt_f,
                        ((( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'M' and u2.ocupacao = o.ocupacao #CREAS)   +
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'F' and u2.ocupacao = o.ocupacao #CREAS))
                        /cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') #CREAS) as float)) as perc
			From pcni_assistenciacreas.ocupacao o
			union
			Select 'Ocupação Não Informada'  as resposta, 2,
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'M' and u2.ocupacao is null #CREAS)   as qt_m,
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'F' and u2.ocupacao is null #CREAS)   as qt_f,

                        ((( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'M' and u2.ocupacao is null #CREAS)  +
			( Select count(*) from pcni_assistenciacreas.familia u2 where u2.sexopessoafamilia = 'F' and u2.ocupacao is null #CREAS)   )/cast((select count(*) from pcni_assistenciacreas.familia where sexopessoafamilia in ('M','F') #CREAS) as float)) as perc
			From pcni_assistenciacreas.ocupacao where ocupacao = 1
			Order by 5 desc";

              $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
              $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="70%" border="1">
            <tr>
              	<td align="center" rowspan="2"><b>Ocupação</b></td>
                <td align="center" colspan="3"><b>Quantidade</b></td>
                <td align="center" colspan="3"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
		<td align="center"><b>Total</b></td>
                <td align="center"><b>Masculino</b></td>
                <td align="center"><b>Feminino</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_m = 0;
               $qt_f = 0;

                while ($row = pg_fetch_array($result,$i))
		        {
                 	$qt_m = $qt_m + $row["qt_m"];
                        $qt_f = $qt_f + $row["qt_f"];                     
                }
                
                $qt_tot_geral = $qt_m + $qt_f;


               pg_result_seek($result, 0);

             	while ($row = pg_fetch_array($result,$i))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_m"];  ?></td>
                <td align="right"><? echo $row["qt_f"];  ?></td>
                <td align="right"><? echo $row["qt_f"] + $row["qt_m"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_m"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_f"] / $qt_tot_geral)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_m; ?></b></td>
                <td align="right"><b><? echo $qt_f; ?></b></td>
                <td align="right"><b><? echo $qt_f + $qt_m; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_m / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_f / $qt_tot_geral)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_f+$qt_m) / $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">7. Cruzamento Ocupação x Relação de Parentesco

             <?

                //numero total
              	$sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia where ocupacao is not null #CREAS";
                $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                $result=pg_query($dbh, $sql_ext);

                $row = pg_fetch_array($result);
		$qt_tot_fam = $row["qt"];

                   $sql = "SELECT nomeocupacao as resposta,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 1 and f.ocupacao = o.ocupacao  #CREAS) as qt_resp,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 2 and f.ocupacao = o.ocupacao  #CREAS) as qt_conjuge,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 3 and f.ocupacao = o.ocupacao  #CREAS) as qt_filho,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 4 and f.ocupacao = o.ocupacao  #CREAS) as qt_pai,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 5 and f.ocupacao = o.ocupacao  #CREAS) as qt_avo,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 6 and f.ocupacao = o.ocupacao  #CREAS) as qt_irmao,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 7 and f.ocupacao = o.ocupacao  #CREAS) as qt_sogro,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 8 and f.ocupacao = o.ocupacao  #CREAS) as qt_neto,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 9 and f.ocupacao = o.ocupacao  #CREAS) as qt_padrasto,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 10 and f.ocupacao = o.ocupacao  #CREAS) as qt_outro_parent,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 11 and f.ocupacao = o.ocupacao  #CREAS) as qt_sem,
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 12 and f.ocupacao = o.ocupacao  #CREAS) as qt_outro,


                        (( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 1 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 2 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 3 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 4 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 5 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 6 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 7 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 8 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 9 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 10 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 11 and f.ocupacao = o.ocupacao  #CREAS) +
			( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = 12 and f.ocupacao = o.ocupacao  #CREAS)) /
                        cast((select count(*) from pcni_assistenciacreas.familia where ocupacao is not null #CREAS) as float)  as perc

			FROM pcni_assistenciacreas.ocupacao o
			order by  14 desc
			";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="100%" border="1">
            <tr>
              	<td align="center" rowspan="2"><b>Ocupação</b></td>
                <td align="center" colspan="13"><b>Quantidade</b></td>
                <td align="center" colspan="13"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Resp.</b></td>
                <td align="center"><b>Cônjuge</b></td>
                <td align="center"><b>Filho</b></td>
                <td align="center"><b>Pai/Mãe</b></td>
                <td align="center"><b>Avó/Avô</b></td>
                <td align="center"><b>Irmão</b></td>
                <td align="center"><b>Sogro</b></td>
                <td align="center"><b>Neto</b></td>
                <td align="center"><b>Padrasto</b></td>
                <td align="center"><b>Outro Parent.</b></td>
                <td align="center"><b>Sem Parent.</b></td>
                <td align="center"><b>Outro</b></td>
                <td align="center"><b>Total</b></td>

                <td align="center"><b>Resp.</b></td>
                <td align="center"><b>Cônjuge</b></td>
                <td align="center"><b>Filho</b></td>
                <td align="center"><b>Pai/Mãe</b></td>
                <td align="center"><b>Avó/Avô</b></td>
                <td align="center"><b>Irmão</b></td>
                <td align="center"><b>Sogro</b></td>
                <td align="center"><b>Neto</b></td>
                <td align="center"><b>Padrasto</b></td>
                <td align="center"><b>Outro Parent.</b></td>
                <td align="center"><b>Sem Parent.</b></td>
                <td align="center"><b>Outro</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
		$qt_resp = 0;
		$qt_conjuge = 0;
		$qt_filho = 0;
		$qt_pai = 0;
		$qt_avo = 0;
		$qt_irmao = 0;
		$qt_sogro = 0;
		$qt_neto = 0;
		$qt_padrasto = 0;
		$qt_outro_parent = 0;
		$qt_sem = 0;
		$qt_outro = 0;


                while ($row = pg_fetch_array($result))
		 {
                       $qt_resp = $qt_resp + $row["qt_resp"];
		       $qt_conjuge = $qt_conjuge + $row["qt_conjuge"];
		       $qt_filho = $qt_filho +$row["qt_filho"];
		       $qt_pai = $qt_pai + $row["qt_pai"];
		       $qt_avo = $qt_avo + $row["qt_avo"];
		       $qt_irmao = $qt_irmao + $row["qt_irmao"];
		       $qt_sogro = $qt_sogro + $row["qt_sogro"];
		       $qt_neto = $qt_neto + $row["qt_neto"];
		       $qt_padrasto = $qt_padrasto + $row["qt_padrasto"];
		       $qt_outro_parent = $qt_outro_parent + $row["qt_outro_parent"];
		       $qt_sem = $qt_sem + $row["qt_sem"];
		       $qt_outro = $qt_outro + $row["qt_outro"];
                 }

                pg_result_seek($result, 0);

             	while ($row = pg_fetch_array($result))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_resp"];  ?></td>
                <td align="right"><? echo $row["qt_conjuge"];  ?></td>
                <td align="right"><? echo $row["qt_filho"];  ?></td>
                <td align="right"><? echo $row["qt_pai"];  ?></td>
                <td align="right"><? echo $row["qt_avo"];  ?></td>
                <td align="right"><? echo $row["qt_irmao"];  ?></td>
                <td align="right"><? echo $row["qt_sogro"];  ?></td>
                <td align="right"><? echo $row["qt_neto"];  ?></td>
                <td align="right"><? echo $row["qt_padrasto"];  ?></td>
                <td align="right"><? echo $row["qt_outro_parent"];  ?></td>
                <td align="right"><? echo $row["qt_sem"];  ?></td>
                <td align="right"><? echo $row["qt_outro"];  ?></td>
                <td align="right"><? echo $row["qt_outro"] + $row["qt_resp"] + $row["qt_conjuge"] + $row["qt_filho"] +  $row["qt_pai"] + $row["qt_avo"] + $row["qt_irmao"]+ $row["qt_sogro"] + $row["qt_neto"] + $row["qt_padrasto"] + $row["qt_outro_parent"] + $row["qt_sem"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_resp"] / $qt_resp)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_conjuge"] / $qt_conjuge)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_filho"] / $qt_filho)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_pai"] / $qt_pai)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_avo"] / $qt_avo)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_irmao"] / $qt_irmao)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_sogro"] / $qt_sogro)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_neto"] / $qt_neto)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_padrasto"] / $qt_padrasto)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_outro_parent"] / $qt_outro_parent)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_sem"] / $qt_sem)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_outro"] / $qt_outro)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>

	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_resp; ?></b></td>
                <td align="right"><b><? echo $qt_conjuge; ?></b></td>
                <td align="right"><b><? echo $qt_filho; ?></b></td>
                <td align="right"><b><? echo $qt_pai; ?></b></td>
                <td align="right"><b><? echo $qt_avo; ?></b></td>
                <td align="right"><b><? echo $qt_irmao; ?></b></td>
                <td align="right"><b><? echo $qt_sogro; ?></b></td>
                <td align="right"><b><? echo $qt_neto; ?></b></td>
                <td align="right"><b><? echo $qt_padrasto; ?></b></td>
                <td align="right"><b><? echo $qt_outro_parent; ?></b></td>
                <td align="right"><b><? echo $qt_sem; ?></b></td>
                <td align="right"><b><? echo $qt_outro; ?></b></td>
                <td align="right"><b><? echo $qt_outro + $qt_resp + $qt_conjuge + $qt_filho +  $qt_pai + $qt_avo + $qt_irmao+ $qt_sogro + $qt_neto + $qt_padrasto + $qt_outro_parent + $qt_sem; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_resp / $qt_resp)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_conjuge / $qt_conjuge)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_filho / $qt_filho)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_pai / $qt_pai)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_avo / $qt_avo)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_irmao / $qt_irmao)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_sogro / $qt_sogro)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_neto / $qt_neto)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_padrasto / $qt_padrasto)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_outro_parent / $qt_outro_parent)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_sem / $qt_sem)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_outro / $qt_outro)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_outro + $qt_resp + $qt_conjuge + $qt_filho +  $qt_pai + $qt_avo + $qt_irmao+ $qt_sogro + $qt_neto + $qt_padrasto + $qt_outro_parent + $qt_sem) / $qt_tot_fam)*100,2,',','.'); ?></b></td>

              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4">8. Declarantes com Renda do Trabalho x Idade

             <?
                         //numero total
	              	$sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia where idadepessoafamilia  >= 15  #CREAS";
                        $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                        $result=pg_query($dbh, $sql_ext);

	                $row = pg_fetch_array($result);
			$qt_tot_fam = $row["qt"];

                        $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia where temrendatrabalhomembrofamilia in ('S') and idadepessoafamilia  >= 15  #CREAS";
                        $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                        $result=pg_query($dbh, $sql_ext);

	                $row = pg_fetch_array($result);
			$qt_tot_sim = $row["qt"];

                        $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia where temrendatrabalhomembrofamilia in ('N') and idadepessoafamilia  >= 15  #CREAS";
                        $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                        $result=pg_query($dbh, $sql_ext);

	                $row = pg_fetch_array($result);
			$qt_tot_nao = $row["qt"];


                        $sql_ext = " Select count(*) as qt from pcni_assistenciacreas.familia where temrendatrabalhomembrofamilia in ('X') and idadepessoafamilia  >= 15  #CREAS";
                        $sql_ext = str_replace("#CREAS",$filtro_CREAS,$sql_ext);
                        $result=pg_query($dbh, $sql_ext);

	                $row = pg_fetch_array($result);
			$qt_tot_ns = $row["qt"];

                        $qt_tot_nr = $qt_tot_fam - ($qt_tot_sim + $qt_tot_nao + $qt_tot_ns);

                            $sql = "
 				select '15 a 19' as resposta, 4 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.temrendatrabalhomembrofamilia = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.temrendatrabalhomembrofamilia = 'N' #CREAS) as qt_nao,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.temrendatrabalhomembrofamilia = 'X' #CREAS) as qt_ns,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 and u2.temrendatrabalhomembrofamilia is null #CREAS) as qt_nr,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 15 and 19 #CREAS)/cast((Select count(*) as qt from pcni_assistenciacreas.familia where idadepessoafamilia  >= 15  #CREAS) as float) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 15 and 19  #CREAS group by 1
			union
			select '20 a 29' as resposta, 5 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.temrendatrabalhomembrofamilia = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.temrendatrabalhomembrofamilia = 'N' #CREAS) as qt_nao,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.temrendatrabalhomembrofamilia = 'X' #CREAS) as qt_ns,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 and u2.temrendatrabalhomembrofamilia is null #CREAS) as qt_nr,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 20 and 29 #CREAS)/cast((Select count(*) as qt from pcni_assistenciacreas.familia where idadepessoafamilia  >= 15  #CREAS) as float) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 20 and 29  #CREAS group by 1
			union
			select '30 a 59' as resposta, 6 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.temrendatrabalhomembrofamilia = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.temrendatrabalhomembrofamilia = 'N' #CREAS) as qt_nao,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.temrendatrabalhomembrofamilia = 'X' #CREAS) as qt_ns,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 and u2.temrendatrabalhomembrofamilia is null #CREAS) as qt_nr,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  between 30 and 59 #CREAS)/cast((Select count(*) as qt from pcni_assistenciacreas.familia where idadepessoafamilia  >= 15  #CREAS) as float) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  between 30 and 59  #CREAS group by 1
			union
			select '60+' as resposta, 7 as ordem,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.temrendatrabalhomembrofamilia = 'S' #CREAS) as qt_sim,
			(select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.temrendatrabalhomembrofamilia = 'N' #CREAS) as qt_nao,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.temrendatrabalhomembrofamilia = 'X' #CREAS) as qt_ns,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >= 60 and u2.temrendatrabalhomembrofamilia is null #CREAS) as qt_nr,
                        (select count(*) from pcni_assistenciacreas.familia u2 where idadepessoafamilia  >=60 #CREAS)/cast((Select count(*) as qt from pcni_assistenciacreas.familia where idadepessoafamilia  >= 15  #CREAS) as float) as perc
			from pcni_assistenciacreas.familia u
			where  idadepessoafamilia  >= 60  #CREAS group by 1
			order by 7 desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="60%" border="1">
            <tr>
              	<td align="center" rowspan="2"><b>Faixa Etária</b></td>
                <td align="center" colspan="5"><b>Quantidade</b></td>
                <td align="center" colspan="5"><b>Percentual</b></td>
              </tr>
              <tr>
                <td align="center"><b>Possui Renda</b></td>
                <td align="center"><b>Não Possui Renda</b></td>
                <td align="center"><b>Não Sabe/Não Respondeu</b></td>
                <td align="center"><b>Sem Declaração</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Possui Renda</b></td>
                <td align="center"><b>Não Possui Renda</b></td>
                <td align="center"><b>Não Sabe/Não Respondeu</b></td>
                <td align="center"><b>Sem Declaração</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_sim = 0;
               $qt_nao = 0;
               $qt_ns = 0;
               $qt_nr = 0;

             	while ($row = pg_fetch_array($result,$i))
		 {
                 	$qt_sim = $qt_sim + $row["qt_sim"];
                        $qt_nao = $qt_nao + $row["qt_nao"];
                        $qt_ns = $qt_ns + $row["qt_ns"];
                        $qt_nr = $qt_nr + $row["qt_nr"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_sim"];  ?></td>
                <td align="right"><? echo $row["qt_nao"];  ?></td>
                <td align="right"><? echo $row["qt_ns"];  ?></td>
                <td align="right"><? echo $row["qt_nr"];  ?></td>
                <td align="right"><? echo $row["qt_nao"] + $row["qt_sim"] + $row["qt_ns"] + $row["qt_nr"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_sim"] / $qt_tot_sim)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao"] / $qt_tot_nao)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_ns"] / $qt_tot_ns)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nr"] / $qt_tot_nr)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_sim; ?></b></td>
                <td align="right"><b><? echo $qt_nao; ?></b></td>
                <td align="right"><b><? echo $qt_ns; ?></b></td>
                <td align="right"><b><? echo $qt_nr; ?></b></td>
                <td align="right"><b><? echo $qt_nao + $qt_sim + $qt_ns + $qt_nr; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_sim / $qt_tot_sim)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao / $qt_tot_nao)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_ns / $qt_tot_ns)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nr / $qt_tot_nr)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_nao + $qt_sim + $qt_ns + $qt_nr) / $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


           <tr>
            <td colspan="4">9. Declarantes com renda do trabalho x Relação de Parentesco

             <?
                            $sql = "select descricaograuparentesco as resposta,
					( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = p.grauparentesco and f.temrendatrabalhomembrofamilia = 'S' and idadepessoafamilia  >= 15 #CREAS) as qt_sim,
					( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = p.grauparentesco and f.temrendatrabalhomembrofamilia = 'N' and idadepessoafamilia  >= 15  #CREAS) as qt_nao,
                                        ( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = p.grauparentesco and f.temrendatrabalhomembrofamilia = 'X' and idadepessoafamilia  >= 15 #CREAS) as qt_ns,
                                        ( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = p.grauparentesco and f.temrendatrabalhomembrofamilia is null and idadepessoafamilia  >= 15 #CREAS) as qt_nr,
                                        ( select count(*) from  pcni_assistenciacreas.familia f where f.grauparentesco = p.grauparentesco and idadepessoafamilia  >= 15 #CREAS) / (cast((select count(*) from  pcni_assistenciacreas.familia where idadepessoafamilia  >= 15 #CREAS) as float)) as perc
					from pcni_assistenciacreas.parentescocreas p
					order by 6 desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);
              $perc = 0;

            ?>
            <br>
            <table width="60%" border="1">
              <tr>
              	<td align="center" rowspan="2"><b>Parentesco</b></td>
                <td align="center" colspan="5"><b>Quantidade</b></td>
                <td align="center" colspan="5"><b>Percentual</b></td>
              </tr>

              <tr>
                <td align="center"><b>Possui Renda</b></td>
                <td align="center"><b>Não Possui Renda</b></td>
                <td align="center"><b>Não Sabe/Não Respondeu</b></td>
                <td align="center"><b>Sem Declaração</b></td>
                <td align="center"><b>Total</b></td>
                <td align="center"><b>Possui Renda</b></td>
                <td align="center"><b>Não Possui Renda</b></td>
                <td align="center"><b>Não Sabe/Não Respondeu</b></td>
                <td align="center"><b>Sem Declaração</b></td>
                <td align="center"><b>Total</b></td>
              </tr>
               <?
               $qt_sim = 0;
               $qt_nao = 0;
               $qt_ns = 0;
	       $qt_nr = 0;
             	while ($row = pg_fetch_array($result))
		 {
                 	$qt_sim = $qt_sim + $row["qt_sim"];
                        $qt_nao = $qt_nao + $row["qt_nao"];
                        $qt_ns = $qt_ns + $row["qt_ns"];
                        $qt_nr = $qt_nr + $row["qt_nr"];
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt_sim"];  ?></td>
                <td align="right"><? echo $row["qt_nao"];  ?></td>
                <td align="right"><? echo $row["qt_ns"];  ?></td>
                <td align="right"><? echo $row["qt_nr"];  ?></td>
                <td align="right"><? echo $row["qt_nao"] + $row["qt_sim"] + $row["qt_ns"] + $row["qt_nr"];  ?></td>
                <td align="right"><? echo number_format(($row["qt_sim"] / $qt_tot_sim)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nao"] / $qt_tot_nao)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_ns"] / $qt_tot_ns)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["qt_nr"] / $qt_tot_nr)*100,2,',','.'); ?></td>
                <td align="right"><? echo number_format(($row["perc"] )*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>
              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_sim; ?></b></td>
                <td align="right"><b><? echo $qt_nao; ?></b></td>
                <td align="right"><b><? echo $qt_ns; ?></b></td>
                <td align="right"><b><? echo $qt_nr; ?></b></td>
                <td align="right"><b><? echo $qt_nao + $qt_sim + $qt_ns + $qt_nr; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_sim / $qt_tot_sim)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nao / $qt_tot_nao)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_ns / $qt_tot_ns)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format(($qt_nr / $qt_tot_nr)*100,2,',','.'); ?></b></td>
                <td align="right"><b><? echo number_format((($qt_nao + $qt_sim + $qt_ns + $qt_nr)/ $qt_tot_fam)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

            </td>
          </tr>


          <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


           <tr>
            <td colspan="4">10. Composição Familiar
            <?	$sql = "select count(*) as qt from
				(
				Select numerocreas, datacadastrousuario, count(*)
				From pcni_assistenciacreas.familia
				where idadepessoafamilia between 0 and 14  #CREAS
				group by numerocreas, datacadastrousuario
				) x order by qt";

            $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
            $result=pg_query($dbh, $sql);
              $row = pg_fetch_array($result) ;
              $perc = 0;

            ?>
            <br>
             <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Famílias com Crianças</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>

              <tr>
              	<td align="left">Entre 0 e 14 anos</b></td>
                <td align="right"><? echo $row["qt"]; ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot)*100,2,',','.'); ?></td>
              </tr>
             <!-- <tr>
              	<td align="left">Acima de 14 anos</b></td>
                <td align="right"><? echo $qt_tot - $row["qt"]; ?></td>
                <td align="right"><? echo number_format((($qt_tot - $row["qt"]) / $qt_tot)*100,2,',','.'); ?></td>
              </tr>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>-->
              </table>

            <br>


             <?
              //numero total resp. mulher
		$sql = "Select count(*)  as qt From
				pcni_assistenciacreas.familia f
				Where sexopessoafamilia = 'F' and grauparentesco = 1 #CREAS";
		$sql = str_replace("#CREAS",$filtro_CREAS,$sql);
		$result=pg_query($dbh, $sql);

		$row = pg_fetch_array($result);
		$qt_tot_fem = $row["qt"];

             $sql = "Select 'Com Companheiro ' as resposta , count(*)  as qt,
                                (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia f Where sexopessoafamilia = 'F' and grauparentesco = 1 #CREAS) as float)) as perc
             			 From
				pcni_assistenciacreas.familia f
				Where sexopessoafamilia = 'F' and grauparentesco = 1   #CREAS
				And Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
					    and f2.grauparentesco = 2 )

				union

				Select 'Sem Companheiro ' as resposta , count(*)  as qt,
                                (Count(*)/cast((select count(*) from pcni_assistenciacreas.familia f Where sexopessoafamilia = 'F' and grauparentesco = 1 #CREAS) as float)) as perc
                                From pcni_assistenciacreas.familia f
				Where sexopessoafamilia = 'F' and grauparentesco = 1  #CREAS
				And not Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
					    and f2.grauparentesco = 2 )
                                order by 3 desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

            ?>
            <br>
             <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Famílias com Responsável do Sexo Feminino</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
             	while ($row = pg_fetch_array($result))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot_fem; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot_fem/$qt_tot_fem)*100,2,',','.'); ?></b></td>
              </tr>
              </table>


                          <br>


             <?

             $sql = "Select 'Nenhum Adulto Trabalha ' as resposta , count(*)  as qt,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
             		 From
			pcni_assistenciacreas.usuario f
			Where
			Not Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
				    and tipopessoafamilia = '2' and ocupacao <> '1')  #CREAS

			union

			Select 'Algum Adulto Trabalha ' as resposta , count(*)  as qt,
                        (Count(*)/cast((select count(*) from pcni_assistenciacreas.usuario where 1=1 #CREAS) as float)) as perc
                        From
			pcni_assistenciacreas.usuario f
			Where
			Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
				    and tipopessoafamilia = '2' and ocupacao <> '1') #CREAS
                    	order by 3 desc ";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

            ?>
            <br>
             <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Famílias onde</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
             	while ($row = pg_fetch_array($result))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["perc"])*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>
              </table>



                <br>


             <?

             $sql = "Select 'Sim ' as resposta , count(*) as qt , 1  as ordem  From
				pcni_assistenciacreas.usuario f
				Where
				Not Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
					    and tipopessoafamilia = '2' and valorrendatrabalhomembrofamilia > 0)  #CREAS

				union

				Select 'Não ' as resposta , count(*) as qt, 2  as ordem From
				pcni_assistenciacreas.usuario f
				Where
				Exists ( select 1 from pcni_assistenciacreas.familia f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario
					    and tipopessoafamilia = '2' and valorrendatrabalhomembrofamilia > 0)  #CREAS
				order by qt desc";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

            ?>
            <br>
             <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Famílias com Renda Zero declarada</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <?
             	while ($row = pg_fetch_array($result))
		 {
                 ?>

                 <tr>
              	<td><? if (!isset($row["resposta"])){ echo "Não sabe/Não respondeu"; } else {echo $row["resposta"];} ?></td>
                <td align="right"><? echo $row["qt"];  ?></td>
                <td align="right"><? echo number_format(($row["qt"] / $qt_tot)*100,2,',','.'); ?></td>
	        </tr>
                 <?
		 }
              ?>

              <tr>
              	<td><b>Totais</b></td>
                <td align="right"><b><? echo $qt_tot; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_tot/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>
              </table>

              <?

             $sql = "Select count(*) as qt  From
				pcni_assistenciacreas.usuario f
				Where
				Not Exists ( select 1 from pcni_assistenciacreas.usuariobeneficio f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario ) #CREAS
                                order by qt ";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

             $row = pg_fetch_array($result);
             $qt_sem_benef = $row["qt"];

            ?>

              <br>
             <table width="50%" border="1">
              <tr>
              	<td align="center"><b>Famílias que</b></td>
                <td align="center"><b>Qtd.</b></td>
                <td align="center"><b>%</b></td>
              </tr>

               <tr>
              	<td>Não receberam nenhum benefício</td>
                <td align="right"><b><? echo $qt_sem_benef; ?></b></td>
                <td align="right"><b><? echo number_format(($qt_sem_benef/$qt_tot)*100,2,',','.'); ?></b></td>
              </tr>

               <?

             $sql = "Select count(*) as qt  From
				pcni_assistenciacreas.usuario f
				Where
				Not Exists ( select 1 from pcni_assistenciacreas.usuariobeneficio f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario )
                                And Exists ( select 1 from pcni_assistenciacreas.familia f3 where f.numerocreas = f3.numerocreas and f.datacadastrousuario = f3.datacadastrousuario and f3.temrendatrabalhomembrofamilia = 'S' )
                                #CREAS ";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

             $row = pg_fetch_array($result);

            ?>
              <tr>
              	<td>Não receberam nenhum benefício com adulto trabalhando</td>
                <td align="right"><b><? echo $row["qt"]; ?></b></td>
                <td align="right"><b><? echo number_format(($row["qt"]/$qt_sem_benef)*100,2,',','.'); ?></b></td>
              </tr>

               <?

             $sql = "Select count(*) as qt  From
				pcni_assistenciacreas.usuario f
				Where
				Not Exists ( select 1 from pcni_assistenciacreas.usuariobeneficio f2 where f.numerocreas = f2.numerocreas and f.datacadastrousuario = f2.datacadastrousuario )
                                And Not Exists ( select 1 from pcni_assistenciacreas.familia f3 where f.numerocreas = f3.numerocreas and f.datacadastrousuario = f3.datacadastrousuario and f3.temrendatrabalhomembrofamilia = 'S' )
                                #CREAS ";

             $sql = str_replace("#CREAS",$filtro_CREAS,$sql);
             $result=pg_query($dbh, $sql);

             $row = pg_fetch_array($result);

            ?>
              <tr>
              	<td>Não receberam nenhum benefício sem adulto trabalhando</td>
                <td align="right"><b><? echo $row["qt"]; ?></b></td>
                <td align="right"><b><? echo number_format(($row["qt"]/$qt_sem_benef)*100,2,',','.'); ?></b></td>
              </tr>

              </table>

            </td>
          </tr>

           <tr>
            <td height="5" colspan="4" bgcolor="#FFFFFF"></td>
            </tr>
          <tr>


          <tr>
            <td colspan="4"><div align="center">
              <input name="voltar" type="button" class="botao" id="voltar" value="voltar" onclick="window.location='main2.php?acao=voltar';"/>
              </div>
            </td>
            </tr>


          </form>


        </table>

      </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>
<div id="footer"><? include "includes/rodape.php"; ?></div>
</body>
</html>

<?
include "includes/end.php";
?>
