不是mysql中的组组函数

时间:2014-11-01 22:22:01

标签: mysql oracle

我有一张表(发票),如

InovoiceID     Invoice amount    

我想选择invoicenumber,平均invoiceamount,以及每行的实际金额和平均invoiceamount之间的差异。但是,当我尝试这样做时,

select invoiceID, 
       avg(invoiceamount) as Average, 
       Average - invoiceamount
  from invoice

这表示sql命令未完成的错误。

为什么会这样?

PS:我甚至试过这个,

SELECT invoiceid, 
       (SELECT AVG(invoiceamount) FROM Invoice) AS avg_invamt, 
       (SELECT AVG(invoiceamount) FROM Invoice) - invoiceamount AS diff 
  FROM Invoice

但它仍显示错误。 我正在使用oracle数据库快递版。

2 个答案:

答案 0 :(得分:0)

这似乎是一个有益于窗口函数的查询 但是,MySQL不支持这些功能。下面的查询应该有效。

SELECT invoiceId, avg_inv.amt AS "Average", 
avg_inv.amt - invoice.invoiceamount AS "Difference"
FROM invoice, 
(SELECT avg(invoiceamount) as "amt" FROM invoice) avg_inv

更新:刚刚注意到问号标签已从mysql更改为oracle。现在你可以使用窗口函数了。

heres a description of their usage in oracle,或者你可以搜索关于窗口函数的无数SO问题。

答案 1 :(得分:0)

由于您在没有指定group group语句的情况下使用组函数,因此您要做的就是group by错误。因此,您可以通过子查询甚至使用with子句实现所需的目标。

在我的例子中,我改变了一些列的名称。

with a as (
    select avg(amount) average
      from invoice
    )
select id, a.average, a.average - amount as diff
  from invoice, a;

OR

select id, a.average, a.average - amount as diff
  from invoice, 
       (select avg(amount) average
          from invoice) a;

在sqlfiddle上查看:http://sqlfiddle.com/#!4/0c33e/8