sql命令未正确结束添加,必须限制要显示的数据集

u4vypkhs  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(327)

我正在限制一个数据集只包含sum(a)+sum(b)>avg(a.inv)的行,这里我做错了什么?

`SELECT a.product pno,substr(b.descriptn,1,40) pdesc, 
avg(a.inv) i,avg(a.badinv) q, avg(a.wipc) invc, avg(a.wipq) 
invq, sum(a) suma, sum(b) sumb, sum(c) sumc, sum(d) sumd
FROM temp2 a, mastertbl b 
a.product =b.product 
GROUP BY a.product, b.descriptn 
HAVING sum(sum(a)+sum(b)) > avg(a.inv)
ORDER BY a.product;`
t40tm48m

t40tm48m1#

嵌套的 sum() 是不需要的 having 条款。你可能想要:

HAVING sum(a) + sum(b) > avg(a.inv)

旁注:总是使用标准的显式连接,而不是老式的隐式连接——而且,事实上,您的查询缺少一个 WHERE 条款。此外,有意义的表别名使查询更易于编写和读取。我可以这样说:

SELECT 
    t.product pno,
    substr(m.descriptn,1,40) pdesc, 
    avg(t.inv) i,
    avg(t.badinv) q, 
    avg(t.wipc) invc, 
    avg(t.wipq) invq, 
    sum(a) suma, 
    sum(b) sumb, 
    sum(c) sumc, 
    sum(d) sumd
FROM temp2 t
INNER JOIN mastertbl m ON m.product = t.product 
GROUP BY t.product, m.descriptn 
HAVING HAVING sum(a) + sum(b) > avg(t.inv)
ORDER BY t.product

在这个多表查询中,应该用列所属的表限定所有列的名称:这适用于列 a , b , c , d .

uajslkp6

uajslkp62#

我的建议是:

SELECT *
  FROM
  (
    SELECT 
      t.product pno,
      substr(m.descriptn,1,40) pdesc, 
      avg(t.inv) i,
      avg(t.badinv) q, 
      avg(t.wipc) invc, 
      avg(t.wipq) invq, 
      sum(a) suma, 
      sum(b) sumb, 
      sum(c) sumc, 
      sum(d) sumd
    FROM temp2 t
    INNER JOIN mastertbl m ON m.product = t.product 
    GROUP BY t.product, m.descriptn ) 
WHERE suma + sumb > i
ORDER BY pno

相关问题