2
I need help to build a query that brings data from 5 other tables. I will try to be as clear as possible, in case information is lacking, please inform me.
Come on:
I have the Midias table: http://jotacomdigital.com.br/imgs/midias.png
and the Proposals table: http://jotacomdigital.com.br/imgs/propostas.png
The other 3 tables is quiet, because I just need to bring a field, not needing sums or any other function.
The result must be this:
http://jotacomdigital.com.br/imgs/resultado.png
My Current query is this:
SELECT
data_proposta,
propostas.source_code,
sum(midias.custo) as custo,
COUNT(data_proposta) AS propostas,
SUM(if(precog_FK <> 9, 1, 0)) AS validas
FROM propostas
LEFT JOIN midias
ON `data_proposta` = `midias`.`data`
GROUP BY data_proposta
I’m in trouble when I have to do the sums of the media table costs.
@Felipe I took a test and it didn’t go very well. I changed the query to this: SELECT date_format(a.data_proposed,'%d-%m-%Y') AS data1, date_format(b.data,'%d-%m-%Y') AS data2, a.source_code, sum(b.cost) AS cost, COUNT(a.data_proposed) Proposals, sum(if(a.precog_FK <> 9, 1, 0)) AS validates FROM proposals a, midias b LEFT JOIN midias ON data1 = data2 GROUP BY data_proposition is showing error #1054 - Unknown column 'data1' in 'on clause'
– DeBarros
@Debarros I apologize, I made a mistake. I changed the query, I put "Midas" and not "midias" in the table name.
– Filipe Moraes
@Felipe, didn’t roll no man.
– DeBarros
@So I got your problem wrong, I’m analyzing it better. Is there any connection between the media table and proposals? any id?
– Filipe Moraes
There is no relationship declared in the database, but there is the code (source_code) that is repeated in the tables and also the dates. I’m thinking the problem might be in SUM().
– DeBarros
@Check the column "source_code" is unique in the table of proposals?
– Filipe Moraes
Only in the primarykey sense? No. It can be repeated. But if you want to know if in the proposed table there is another 'source_code', no.There is no such thing.
– DeBarros
@Debarros created the tables here and changed the post above, see if it solves the problem.
– Filipe Moraes
The precog_FK, when different from 9 indicates that it is approved, so I want the amount of it. That’s why I use the SUM in the precog_FK.
– DeBarros
@You must ok, I understand, but if using the information this way will be repeated on all lines, wouldn’t it be better to do a query just for this instead of doing a SUM on all lines? Fewer resources consumed when executing the query. This new query solved the problem?
– Filipe Moraes
let’s go continue this discussão in chat
– DeBarros