Doubt how to mount a query in Mysql

Asked

Viewed 53 times

0

SELECT 
  `tab_banco`.`nome` AS `bancoNome`,
  `conta_bancaria`.`conta_apelido` AS `contaApelido`,
  `conta_bancaria`.`id` AS `idConta`,
  `movimento`.`conta_bancaria_id` AS `conta_bancaria_id`,
  `tabehist`.`HIST_Codigo` AS `codigoHistorico`,
  `tabehist`.`HIST_Descricao` AS `descricaoHistorico`,
  YEAR(`movimento`.`data_lancamento`) AS `ano`,
  SUM(
    (
      CASE
        WHEN (
          (
            `movimento_historico`.`historico_id` <= 499
          ) 
          AND (
            (`movimento`.`pendente` = 0) + (`movimento`.`pendente` = 1)
          ) 
          AND (
            `movimento_historico`.`historico_id` = `tabehist`.`HIST_Codigo`
          ) 
          AND (
            MONTH(`movimento`.`data_lancamento`) = 1
          ) 
          AND (
            YEAR(`movimento`.`data_lancamento`) = 2018
          )
        ) 
        THEN `movimento_historico`.`valor` 
        ELSE 0 
      END
    )
  ) AS `debitos1` 

  FROM ((((`conta_bancaria`
      JOIN `tab_banco`
        ON ((`conta_bancaria`.`tab_banco_id` = `tab_banco`.`id`)))
     JOIN `movimento`
       ON ((`conta_bancaria`.`id` = `movimento`.`conta_bancaria_id`)))
    JOIN `movimento_historico`
      ON ((`movimento`.`id` = `movimento_historico`.`movimento_id`)))
   LEFT JOIN `tabehist`
     ON ((`movimento_historico`.`historico_id` = `tabehist`.`HIST_Codigo`)))
WHERE (`movimento`.`visivel` = 1)
GROUP BY `movimento`.`conta_bancaria_id`,`codigoHistorico`

The above query assembles a data report, but it has one but I am not managing to leave the values of the years separate, the same ones are blending, today I have set the year 2018 as follows:
... AND (YEAR(movimento.data_lancamento) = 2018 ) but I want to make it dynamic so I can separate those years.

1 answer

0

These filter that you used in the case, put it in the clause Where at the bottom, and in the case you filter only the years.

Following example:

SELECT SUM(CASE WHEN(YEAR(DATA)) = 2017 THEN SUM(VALOR) ELSE 0 END) AS [2017],
       SUM(CASE WHEN(YEAR(DATA)) = 2018 THEN SUM(VALOR) ELSE 0 END) AS [2018]
       FROM conta_bancaria
       WHERE 'FILTROS' AND YEAR(DATA) BETWEEN '2017-01-01' AND '2018-12-31'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.