我想根据销售的相同数量将我的桌子分成三个产品组。在这个例子中,销售的商品总数是48.所以我想要三组,每组最多可以添加16个项目,如下所示:
ProductName NumberOfItemsSold GroupNumber
Product B 6 1
Product C 5 1
Product A 5 1
Product M 5 2
Product N 4 2
Product G 4 2
Product H 3 2
Product I 3 3
Product K 3 3
Product F 3 3
Product L 2 3
Product E 2 3
Product D 1 3
Product J 1 3
Product O 1 3
这意味着产品B,C& A,卖出的物品有I,K,F,L,E,D,J& O. 我如何计算GroupNumber?我尝试过NTILE,但这不起作用。以下是一些示例SQL:
CREATE TABLE #SalesNumbers
(
ProductName VARCHAR(20),
NumberOfItemsSold INT
)
INSERT INTO #SalesNumbers VALUES ('Product A', 5)
INSERT INTO #SalesNumbers VALUES ('Product B', 6)
INSERT INTO #SalesNumbers VALUES ('Product C', 5)
INSERT INTO #SalesNumbers VALUES ('Product D', 1)
INSERT INTO #SalesNumbers VALUES ('Product E', 2)
INSERT INTO #SalesNumbers VALUES ('Product F', 3)
INSERT INTO #SalesNumbers VALUES ('Product G', 4)
INSERT INTO #SalesNumbers VALUES ('Product H', 3)
INSERT INTO #SalesNumbers VALUES ('Product I', 3)
INSERT INTO #SalesNumbers VALUES ('Product J', 1)
INSERT INTO #SalesNumbers VALUES ('Product K', 3)
INSERT INTO #SalesNumbers VALUES ('Product L', 2)
INSERT INTO #SalesNumbers VALUES ('Product M', 5)
INSERT INTO #SalesNumbers VALUES ('Product N', 4)
INSERT INTO #SalesNumbers VALUES ('Product O', 1)
--SELECT * FROM #SalesNumbers
--ORDER BY NumberOfItemsSold DESC
--SELECT SUM(NumberOfItemsSold) FROM #SalesNumbers
--SELECT SUM(NumberOfItemsSold) / 3 FROM #SalesNumbers
SELECT
ProductName, NumberOfItemsSold,
NTILE(3) OVER (ORDER BY NumberOfItemsSold DESC) AS GroupNumber
FROM #SalesNumbers
DROP TABLE #SalesNumbers
(我意识到我的数字并不总是适合分组和加起来像我的例子一样好的组)