Search code examples
mysqlsqlmysql-error-1064

MySQL Having clause with a Correlated query is not working


I have a problem in my having clause. I want to compare between two sum having the same Bid but different sens fields I get this output:

SELECT v.bid 
FROM   v1 v 
WHERE  sens = 'c' 
GROUP  BY bid 
HAVING Sum(mont) < (SELECT Sum(l.mont) 
                    FROM   v1 l 
                    WHERE  sens = 'd' 
                           AND l.bid = v.bid group by l.bid); 

ERROR 1054 (42S22): Field 'v.bid unknown in field list`

Edit : V1 is a view, i used aliases l and v trying to ling the sub query to the main query

Sorry guys thank you all for your answers, i was having an issue wuth the columns of the original table and now it is solved :)


Solution

  • No need for two selects from this table, you can use CASE EXPRESSION for this purpose :

    SELECT v.bid FROM v1 v
    GROUP BY v.bid
    HAVING SUM(CASE WHEN v.sens = 'c' THEN v.mont ELSE 0 END) <
           SUM(CASE WHEN v.sens = 'd' THEN v.mont ELSE 0 END) 
       AND COUNT(CASE WHEN v.sens = 'c' THEN 1 END) > 0