Busca por mês

6 respostas
V

Olá,

Preciso fazer um cálculo total de despesas por mês, o meu campo data segue o padrão aaaa/mm/dd e tenho o seguinte select que faz o cálculo total:

public String findTotal() throws Exception {
	
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
        try {          
            conn = Pool.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("SELECT REPLACE(SUM(REPLACE(valor, ',', '.')), '.', ',') total FROM Despesa");
            if (rs.next())
            	return rs.getString("total")==null?"0,00":rs.getString("total");
		} finally {
			Util.freeResources(new Object[] { conn, st, rs });
		}
        return "0,00";

	}

Alguém sabe como alterar o select para fazer a busca mensal, talvez precise vir um outro parâmetro mês.

Obrigado,
Vinicius.

6 Respostas

klarq

Use o group by:

select count (valor) from despesa group by data

qq coisa posta os campos da sua tabela ai 8) :wink:

V
DROP TABLE IF EXISTS `dbcbcon`.`despesa`;
CREATE TABLE  `dbcbcon`.`despesa` (
  `idDespesa` bigint(20) unsigned NOT NULL auto_increment,
  `idPlanoContas` bigint(20) unsigned NOT NULL default '0',
  `observacao` varchar(255) NOT NULL default '',
  `valor` varchar(10) NOT NULL default '',
  `data` date NOT NULL default '0000-00-00',
  `situacao` varchar(45) NOT NULL default '',
  PRIMARY KEY  (`idDespesa`),
  KEY `FK_DespesaPlanoContas` (`idPlanoContas`),
  CONSTRAINT `FK_DespesaPlanoContas` FOREIGN KEY (`idPlanoContas`) REFERENCES `planocontas` (`idPlanoContas`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
T

A sua data não é que está por ano-mês-dia.
Ela é um campo Date.
Nesse caso é melhor usar as funções adequadas.

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

Para saber as despesas do mês de janeiro:

select despesa where data between ‘2006-01-01’ and ‘2006-01-31’

V

Teria como fazer algo desse dipo:

Eu consigo pegar o mês e o ano, então:

public String findTotalEfetivo(String mes, String ano) throws Exception {
		
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
        try {          
            conn = Pool.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("SELECT REPLACE(SUM(REPLACE(valor, ',', '.')), '.', ',') total FROM Despesa where situacao='Efetuada' and data = '"+ano-mes+"??'");
            
            if (rs.next())
            	return rs.getString("total")==null?"0,00":rs.getString("total");
		} finally {
			Util.freeResources(new Object[] { conn, st, rs });
		}
        return "0,00";

	}

Teria como fazer algo desse tipo?

V

Olá,

Esse código funcionou:

public String findTotalEfetivo(String mes, String ano) throws Exception {
		
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
        try {          
            conn = Pool.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("SELECT REPLACE(SUM(REPLACE(valor, ',', '.')), '.', ',') total FROM Despesa where situacao='Efetuada' and data = '"+ano+"-"+mes+"-03'");
            
            if (rs.next())
            	return rs.getString("total")==null?"0,00":rs.getString("total");
		} finally {
			Util.freeResources(new Object[] { conn, st, rs });
		}
        return "0,00";

	}

O único problema agora e fazer com que o dia seja qualquer um, para somar os dados do mês inteiro.

Alguém sabe fazer isso?

Vinicius.

klarq

Dê uma olhado no link do mysql para usar funções de data e pegar somente o mês:

thingol:
Nesse caso é melhor usar as funções adequadas.

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

é mais simples do que você pensa… 8)

Criado 3 de maio de 2006
Ultima resposta 3 de mai. de 2006
Respostas 6
Participantes 3