我必须建立一个查询,该查询显示并计算交易数据中最频繁的产品。在这种情况下,某一天我们可以有多个产品线,但是查询应考虑整个数据。
例如,从下面的数据中,我们可以看到产品“平板电脑”是最受欢迎的产品,销售额最高。但是,我们还可以观察到,该商品在7天内仅售出2天。
另一方面,从数据的开始到结束,每天都销售“清洁剂”产品。
在这种情况下,外观的总和无法正常工作,因为某些产品可能在一天之内需求量很大,但在接下来的五天内还没有购买任何产品。查询结果应为“清洁剂”是每天购买的产品。
Date |Product ID|Product|QTY|Price
02.01.19|HK2345|tablet |2 |1500
02.01.19|HK2345|tablet |2 |1500
02.01.19|FG4549|phone |4 |800
02.01.19|DF2345|mouse |5 |20
02.01.19|KO4865|monitor |1 |450
02.01.19|SDF486|coffe mach |6 |300
02.01.19|POIJ48|cleaner |1 |20
03.01.19|KO4GR |surround |2 |450
03.01.19|SDFGEA|vaccum clea|8 |300
03.01.19|POIJ48|cleaner |9 |20
04.01.19|HK2KOI|charger |1 |15
04.01.19|HK2KOJ|cooler |1 |20
04.01.19|HK2GDS|mouse pad |10 |8
04.01.19|FG4549|phone |4 |800
04.01.19|POIJ48|cleaner |1 |20
04.01.19|POIJ48|cleaner |9 |20
05.01.19|49894U|chair |1 |100
05.01.19|49894U|chair |5 |100
05.01.19|POIJ48|cleaner |9 |20
05.01.19|JIPIO4|book |1 |20
05.01.19|NGGO7|lamp |1 |80
06.01.19|HK2KOI|charger |1 |15
06.01.19|POIJ48|cleaner |9 |20
07.01.19|48961G|keybord |11 |20
07.01.19|POIJ48|cleaner |9 |20
07.01.19|HRF584|headset |2 |40
08.01.19|GRS4984|fiber cabl|10 |10
08.01.19|DGFE4 |magazine |1 |5
08.01.19|POIJ48|cleaner |9 |20
08.01.19|49894U|chair |5 |100
08.01.19|DF2345|mouse |5 |20
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |12 |1500
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |2 |1500
08.01.19|HK2345|tablet |8 |1500
08.01.19|HK2345|tablet |2 |1500
答案 0 :(得分:1)
您可以对Product
进行分组,并根据销售天数(count(distinct Date)
)进行排序:
select Procuct
, count(distinct Date) as NumberOfDaysWithSales
, sum(Qty) as TotalSold
, sum(Qty*Price) as TotalRevenue
from YourTable
group by
Product
order by
count(distinct Date) desc
答案 1 :(得分:0)
如果您希望通过数据中的天数获得“最受欢迎”的产品,则需要这样的查询:
select top (1) with ties product, count(distinct date) as num_days
from t
group by product
order by num_days desc;
with ties
考虑到通过此度量,多个产品可能都具有相同的受欢迎程度。如果您想按产品总数打破平局,则:
select top (1) with ties product,
count(distinct date) as num_days,
sum(qty) as total_qty
from t
group by product
order by num_days desc, total_qty desc;
再一次,仍然会有联系。