Javascript 根据SQL中的销售百分比创建客户群
我的数据集如下所示 我想用下面的逻辑创建最后一个列集群。需要始终在群集中拾取前3个ID。但有一个条件,在选择前3个ID后,检查该组每个ID的个人ID百分比是否小于等于70。例如,对于ID=1,同样地,对于ID=2500/1000+500+400,检查%为1000/1000+500+400。我们需要检查此组的个人ID。这里,对于所有3个ID,我们都有%SQL Server代码Javascript 根据SQL中的销售百分比创建客户群,javascript,sql,Javascript,Sql,我的数据集如下所示 我想用下面的逻辑创建最后一个列集群。需要始终在群集中拾取前3个ID。但有一个条件,在选择前3个ID后,检查该组每个ID的个人ID百分比是否小于等于70。例如,对于ID=1,同样地,对于ID=2500/1000+500+400,检查%为1000/1000+500+400。我们需要检查此组的个人ID。这里,对于所有3个ID,我们都有%SQL Server代码 --create table customers --( product varchar (200),
--create table customers
--( product varchar (200),
--ids int,
--sales numeric(18,4)
--);
--INSERT into customers values ('A',1,1000);
--INSERT into customers values ('A',2,500);
--INSERT into customers values ('A',3,400);
--INSERT into customers values ('A',4,300);
--INSERT into customers values ('A',5,70);
--INSERT into customers values ('A',6,50);
--INSERT into customers values ('A',7,40);
--INSERT into customers values ('A',8,30);
--INSERT into customers values ('A',9,30);
--INSERT into customers values ('A',10,30);
--INSERT into customers values ('A',11,20);
SET NOCOUNT ON;
DECLARE @Id INT=0,
@cluster INT=1,
@max_irow INT ,
@max_cust_id INT
IF OBJECT_ID('tempdb..#Customers') IS NOT NULL
DROP TABLE #Customers
SELECT ROW_NUMBER() OVER (ORDER BY ids) AS irow,
Product,
Ids,
ISNULL(Sales,0.00) AS Sales,
0 AS Cluster
INTO #Customers
FROM customers WITH(NOLOCK)
SELECT @max_cust_id=@@ROWCOUNT
IF OBJECT_ID('tempdb..#tmp_Cluster') IS NOT NULL
DROP TABLE #tmp_Cluster
SELECT *,CAST(0.0000 AS NUMERIC) AS Percntg
INTO #tmp_Cluster
FROM #Customers WHERE 1=2
WHILE(1=1)
BEGIN
INSERT INTO #tmp_Cluster(irow,Product,Ids,Sales,Cluster,Percntg )
SELECT irow,product,ids,sales,@cluster,sales/SUM(sales) OVER (PARTITION BY ISNULL(Cluster,1))*100
FROM #Customers
WHERE Cluster=0 AND irow<=@Id+3
IF @@ROWCOUNT<3
BREAK;
WHILE(1=1)
BEGIN
IF EXISTS(SELECT 1 FROM #tmp_Cluster WHERE Percntg>=70.00)
BEGIN
SET @max_irow=NULL
SELECT @max_irow=MAX(irow) FROM #tmp_Cluster
TRUNCATE TABLE #tmp_Cluster
INSERT INTO #tmp_Cluster(irow,Product,Ids,Sales,Cluster,Percntg)
SELECT irow,product,ids,sales,@cluster,sales/SUM(sales) OVER(PARTITION BY ISNULL(Cluster,1))*100.00
FROM #Customers
WHERE Cluster=0 AND irow<=@max_irow+1
END
IF NOT EXISTS(SELECT 1 FROM #tmp_Cluster WHERE Percntg>=70.00)
BEGIN
UPDATE A SET A.Cluster= @cluster
FROM #Customers A
INNER JOIN #tmp_Cluster B
ON A.Product=B.Product
AND A.Ids=B.Ids
AND A.irow=B.irow
END
SELECT @Id=MAX(Irow) FROM #Customers WHERE Cluster<>0
SELECT @cluster=MAX(Cluster)+1 FROM #Customers WHERE Cluster<>0
BREAK;
END
TRUNCATE TABLE #tmp_Cluster
END
SELECT Product,Ids,Sales,Cluster FROM #Customers
用您正在使用的数据库标记您的问题。是否总是订购销售?您是否有-ve销售值?