Reduce and simplify redundant sql (mysql) query for financial reporting (account hierarchy)

Asked

Viewed 46 times

1

I have basic knowledge of database and Mysql, I wonder if someone could help me decrease the 'size' of a query and its redundancy (facilitating future maintenance).

This is a financial report with a hierarchy of up to 5 levels, with the top account being a totalizer of the lower level account, successively. To achieve this goal I made a UNION of some Selects, thus getting well redundant.

Example :

Tabelas

Queries:

The first query selects balances for each level 4 account in the hierarchy, then I use this base in the from clause of the next query to retrieve level 3 accounts and so on:

Mysql

 -- base de contas de nível 4
Select  
L.Data, 
H.Conta, 
L.Valor 
From  
lançamentos L 
Inner join  categorias C on C.Categoria = L.categoria 
Inner join hierarquia_de_categorias H on H.conta=C.Hierarquia 

UNION 

-- base de contas de nível 3 Select 
N3.Data,
N3.Conta,
N3.Valor
From 
( -- base de contas de nível 4
Select L.Data, H.Conta, L.Valor From  lançamentos L Inner join categorias C on C.Categoria = L.categoria Inner join hierarquia_de_categorias H on H.conta=C.Hierarquia) n3

UNION
-- base de contas de nível 2 
Select 
N2.Data, 
N2.Conta,
N2.Valor
From 
(
(-- base de contas de nível 3 Select N3.Data, N3.Conta, N3.Valor From ( -- base de contas de nível 4 Select L.Data, H.Conta, L.Valor From  lançamentos L Inner join categorias C on C.Categoria = L.categoria Inner join hierarquia_de_categorias H on H.conta=C.Hierarquia) n3
) n2
 
UNION

-- base de contas de nível 1
Select 
N1.Data,
N1.Conta,
N1.Valor
From
(-- base de contas de nível 2 Select N2.Data, N2.Conta, N2.Valor From ((-- base de contas de nível 3 Select N3.Data, N3.Conta, N3.Valor From ( -- base de contas de nível 4 Select L.Data, H.Conta, L.Valor From  lançamentos L Inner join categorias C on C.Categoria = L.categoria Inner join hierarquia_de_categorias H on H.conta=C.Hierarquia) n3 ) n2 
) n1    

Upshot :

Resultado

No answers

Browser other questions tagged

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