0

我的having子句有问题,这是我遇到的错误:

中的未知tbl_quotes.taxhaving 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) 

谢谢

4

1 回答 1

0

可能使用连接重写并避免代码和计算的一些重复:(
假设:表tbl_quotes作为id主键)

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 ;
于 2013-02-01T22:34:47.230 回答