您如何以不同的价格找到每天不同商品的平均销售量?

时间:2016-07-07 07:35:11

标签: sql sql-server

我是sql的新手,我试图查询以不同的价格查找每天销售的平均产品数量,例如:如果马铃薯有时为2.9 /千克,有时3 /千克,有时3.4 /千克。

我想显示不同的价格和每个价格的平均每日销售量。我尝试进行以下查询,但它没有给我想要的结果:

select i.name, od.price, sum(od.Quantity) / count(datepart(d,o.OrderID))
from orderdetails od
join orders o on(o.orderid=od.orderid)
join item i on(i.itemid=od.itemid)
group by i.name, od.price
order by i.name

问题是,如果某个日期有3个订单中有苹果,它会将订单日期计算3次而不是1次,因为这个日期列出了3次,但实际上我希望它应该计算天数苹果以这个特定的价格出售。

2 个答案:

答案 0 :(得分:0)

for average amount sold per day:

select i.name, od.price, avg(od.Quantity)
from orderdetails od
join orders o on(o.orderid=od.orderid)
join item i on(i.itemid=od.itemid)
group by i.name, od.price, datepart(d,o.OrderID)
order by i.name

for number of days per product/price

select i.name, od.price, count(datepart(d,o.OrderID))
from orderdetails od
join orders o on(o.orderid=od.orderid)
join item i on(i.itemid=od.itemid)
group by i.name, od.price
order by i.name

答案 1 :(得分:0)

我必须根据您的查询对您的数据结构做出一些假设。您似乎只使用Orders的{​​{1}}表格,这也在OrderID中。我假设它是OrderDetails字段,因为您在datetime函数中使用了该字段。

我认为您多次计算天数所遇到的具体问题可以通过我在下面使用的datepart来解决。

这是您的原始查询,略有修改(未经测试,因为没有可用的样本数据)

count distinct

好的,下面是我对此和测试数据的解释。

测试数据

SELECT 
i.name
,od.price
,SUM(od.Quantity) / COUNT(DISTINCT DATEPART(d,o.OrderDate))
FROM orderdetails od
JOIN orders o 
    ON o.orderid = od.orderid
JOIN item i 
    ON i.itemid = od.itemid
GROUP BY i.name, od.price
ORDER BY i.name

查询

IF OBJECT_ID('tempdb..#OrderDetails') IS NOT NULL DROP TABLE #OrderDetails
GO
CREATE TABLE #OrderDetails (OrderID datetime, itemID int, Price money, Quantity int)
INSERT INTO #OrderDetails (OrderID, ItemID, Price, Quantity)
VALUES
 ('2016-07-07 09:00:00', 1, 2.9, 10)
,('2016-07-07 09:30:00', 1, 3.0, 6)
,('2016-07-07 10:50:00', 1, 3.2, 2)
,('2016-07-07 09:00:00', 1, 2.8, 9)
,('2016-07-08 09:00:00', 1, 3.1, 8)
,('2016-07-08 12:30:00', 1, 3.0, 20)
,('2016-07-08 15:52:00', 1, 2.9, 15)
,('2016-07-09 15:52:00', 1, 2.9, 15)
,('2016-07-10 15:52:00', 1, 2.9, 15)

IF OBJECT_ID('tempdb..#Item') IS NOT NULL DROP TABLE #Item
GO
CREATE TABLE #Item (itemID int, Name varchar(10))
INSERT INTO #Item (itemID, Name)
VALUES
(1,'Potatoes')

结果

SELECT
 i.Name Item_Name
,od.Price
,COUNT(DISTINCT CONVERT(date,od.OrderID)) UniqueDays
,SUM(od.Quantity)/COUNT(DISTINCT CONVERT(date,od.OrderID)) AvgSalesPerDay
FROM #OrderDetails od
JOIN #Item i
    ON od.itemID = i.itemID
GROUP BY
    i.Name
    ,od.Price