对于如何获得比所有商店的平均销售额都高的商店的销售额,我似乎找不到解决方案。
我已经尝试了一些方法并设法获得每个商店的平均销售额。然后,我试图使销售额大于所有商店平均水平但失败的商店。
SELECT SALES, (SELECT AVG(AVERSALES * SALES)) AS AVGSALES FROM
(
SELECT
Shops.NAME,
SUM(InvDet.QTY * Products.PRICE ) AS SALES,
AVG(InvDet.QTY * Products.PRICE) AS AVERSALES
FROM
Invoices
INNER JOIN InvDet ON Invoices.INV_ID = InvDet.INV_ID
INNER JOIN Products ON InvDet.PR_ID = Products.PR_ID
INNER JOIN Shops ON Shops.S_ID=Invoices.S_ID
WHERE
Invoices.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
GROUP BY Shops.NAME
)AS SALES_TABLE
GROUP BY SALES
HAVING SALES > (SELECT AVG(AVERSALES))
答案 0 :(得分:0)
您可以通过多种方式获得所需的信息。 其中之一应该是这样:
select
s.name,
s.SALES
from (
select
s.name,
sum(i.QTY * p.PRICE) AS SALES
from Invoices i
join InvDet id ON i.INV_ID = id.INV_ID
join Products p ON id.PR_ID = p.PR_ID
join Shops s ON s.S_ID=i.S_ID
where i.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
group by s.name
) s
join (
select avg(i.QTY * p.PRICE) as average
from Invoices i
join InvDet id ON i.INV_ID = id.INV_ID
join Products p ON id.PR_ID = p.PR_ID
-- If you want to compare with the total average
-- remove this where part
where i.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
) a
on s.SALES>a.average
另一种方法(对我来说更清楚)必须返回相同的结果:
declare @average float
select @average=avg(i.QTY * p.PRICE)
from Invoices i
join InvDet id ON i.INV_ID = id.INV_ID
join Products p ON id.PR_ID = p.PR_ID
-- If you want to compare with the total average
-- remove this where part
where i.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
select
s.name,
sum(i.QTY * p.PRICE) AS SALES
from Invoices i
join InvDet id ON i.INV_ID = id.INV_ID
join Products p ON id.PR_ID = p.PR_ID
join Shops s ON s.S_ID=i.S_ID
where i.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
group by s.name
having sum(i.QTY * p.PRICE)>@average
还有其他选择(例如,通用表表达式在这里也很合适)。我认为有了这两个就足以解决您的问题。我希望它们适合您的需求。
答案 1 :(得分:-1)
我不确定您的要求
SELECT SALES, (SELECT AVG(AVERSALES * SALES)) AS AVGSALES FROM
(
SELECT
Shops.NAME,
SUM(InvDet.QTY * Products.PRICE ) AS SALES,
AVG(InvDet.QTY * Products.PRICE) AS AVERSALES
FROM
Invoices
INNER JOIN InvDet ON Invoices.INV_ID = InvDet.INV_ID
INNER JOIN Products ON InvDet.PR_ID = Products.PR_ID
INNER JOIN Shops ON Shops.S_ID=Invoices.S_ID
WHERE
Invoices.INVOICE_DATE BETWEEN '2013-06-24' AND '2013-06-30'
GROUP BY Shops.NAME
)AS SALES_TABLE
GROUP BY SALES
HAVING SALES > AVERSALES