Group By不会工作

时间:2013-02-01 22:00:58

标签: php mysql

我的has子句出了问题,这是我得到的错误:

tbl_quotes.tax

中的未知列having clause

和我的代码:

SELECT tbl_quotes.docnumber                                      AS docNumber, 
       tbl_quotes.date                                           AS date, 
       Sum(tbl_quotesitems.price) * ( ( tax + tax2 / 100 ) + 1 ) AS total, 
       ( Sum(tbl_quotesitems.price) * ( ( tax + tax2 / 100 ) + 1 ) ) - 
           (SELECT Sum(tbl_payments.amount) 
            FROM tbl_payments 
            WHERE tbl_payments.quoteid = tbl_quotes.id
           )                                                     AS amtOwing 

FROM   tbl_quotes 
       INNER JOIN tbl_quotesitems 
               ON tbl_quotesitems.quoteid = tbl_quotes.id 
GROUP  BY tbl_quotes.id 
HAVING ( Sum(tbl_quotesitems.price) * ( ( ( tbl_quotes.tax + tbl_quotes.tax2 ) / 
                                          100 ) 
                                               + 
                                               1 ) ) < (SELECT Sum( 
                                                       tbl_payments.amount) 
                                                        FROM   tbl_payments 
                                                        WHERE 
              tbl_payments.quoteid = tbl_quotes.id) 

谢谢

1 个答案:

答案 0 :(得分:0)

使用连接进行可能的重写并避免重复代码和计算:
(假设:表格tbl_quotesid为主键)

SELECT q.docnumber  AS docNumber, 
       q.date       AS date, 
       qi.sum_price * ( ( q.tax + q.tax2 / 100 ) + 1 )
                    AS total, 
       qi.sum_price * ( ( q.tax + q.tax2 / 100 ) + 1 ) - p.sum_amount 
                    AS amtOwing 
FROM   tbl_quotes AS q 
       INNER JOIN 
                  ( SELECT   quoteid,
                             SUM(price) AS sum_price
                    FROM     tbl_quotesitems
                    GROUP BY quoteid
                  ) AS qi 
               ON qi.quoteid = q.id 
       INNER JOIN 
                  ( SELECT   quoteid,
                             SUM(amount) AS sum_amount
                    FROM     tbl_payments 
                    GROUP BY quoteid
                  ) AS p  
               ON p.quoteid = q.id
WHERE  qi.sum_price * ( ( ( q.tax + q.tax2 ) / 100 ) + 1 ) 
       < p.sum_amount ;