Compressed Mean

You are trying to find the mean number of items bought per order on Alibaba, rounded to 1 decimal place.

However, instead of doing analytics on all Alibaba orders, you have access to a summary table, which describes how many items were in an order (item_count), and the number of orders that had that many items (order_occurrences).

table name: items_per_order


Solution:

select
format(convert(decimal,sum(item_count * order_occurrences))/sum(order_occurrences),'N1') as mean
from items_per_order

Output:


SQL Script:

CREATE TABLE [dbo].[items_per_order](
       [item_count]
[int] NULL,
       [order_occurrences]
[int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[items_per_order] ([item_count],
[order_occurrences]) VALUES (1, 500)
GO
INSERT [dbo].[items_per_order] ([item_count],
[order_occurrences]) VALUES (2, 1000)
GO
INSERT [dbo].[items_per_order] ([item_count],
[order_occurrences]) VALUES (3, 800)
GO
INSERT [dbo].[items_per_order] ([item_count],
[order_occurrences]) VALUES (4, 1000)
GO


Comments (0)