为Average函数创建SQL查询

时间:2015-11-06 11:26:36

标签: mysql sql-server

我正在尝试编写一个SQL查询来列出发票数量超过每个供应商平均发票数量的供应商。到目前为止,我已经提出了两个问题,但我不确定任何一个是否真实。如果有人能帮帮我的话。

SELECT VENDOR_ID,COUNT(INVOICE_ID), ROUND(AVG(INVOICE_ID), 2)
FROM INVOICES
GROUP BY VENDOR_ID
HAVING COUNT(INVOICE_ID) > AVG(INVOICE_ID)
ORDER BY AVG(INVOICE_ID);

SELECT VENDOR_ID,COUNT(INVOICE_ID), ROUND(AVG(INVOICE_ID), 2)
FROM INVOICES
GROUP BY VENDOR_ID
HAVING AVG(INVOICE_ID) > (SELECT AVG(INVOICE_ID) FROM INVOICES)
ORDER BY AVG(INVOICE_ID);

2 个答案:

答案 0 :(得分:1)

**按照Arth的评论编辑

因此,每个供应商的平均发票数量为:

SELECT cast(COUNT(Invoice_ID) as float) / COUNT(DISTINCT Vendor_Id)
FROM INVOICES

现在让我们将其纳入您的要求

SELECT Vendor_Id, COUNT(Invoice_Id)
FROM INVOICES
GROUP BY Vendor_Id
HAVING COUNT(Invoice_ID) > 
              (SELECT cast(COUNT(Invoice_ID) as float) / COUNT(DISTINCT Vendor_Id) FROM INVOICES)

答案 1 :(得分:0)

我假设这是一个MySQL问题而不是SQL-Server ..这是两个独立的数据库引擎。请选择合适的标签。

首先,听起来您想要平均发票数量,而不是发票ID。要获得平均发票数:

  SELECT AVG(c.invoice_count)
    FROM (
    SELECT COUNT(*) invoice_count
      FROM invoices i
  GROUP BY i.vendor_id
         ) c

我可能会加入这个作为条件:

  SELECT vendor_id, COUNT(*) invoice_count
    FROM invoices
    JOIN ( 
     SELECT AVG(c.invoice_count) avg_invoice_count
       FROM (
       SELECT COUNT(*) invoice_count
         FROM invoices
     GROUP BY vendor_id
            ) c
         ) a
GROUP BY vendor_id
  HAVING invoice_count > a.avg_invoice_count    
ORDER BY invoice_count DESC

正如Steve Ford指出的那样,你可以按如下方式计算AVG:

  SELECT vendor_id, COUNT(*) invoice_count
    FROM invoices
    JOIN ( 
     SELECT CAST(COUNT(*) AS FLOAT)/COUNT(DISTINCT vendor_id) avg_invoice_count
       FROM invoices
         ) a
GROUP BY vendor_id
  HAVING invoice_count > a.avg_invoice_count    
ORDER BY invoice_count DESC