我遇到了一个小问题,我不知道如何进行一轮比赛,希望有人可以提供帮助。我需要做的是在多个记录上运行select并检索p.CustID的最后两个记录。当输入一个p.CustID代码工作正常但我需要删除where子句,我需要它来检索每个p.CustID的最后两个记录(总共大约14,000条记录)当我删除where子句时它只返回两个记录总共是我的语句[DB_User]中的前两个记录。[dbo]。[P1ASellers]。我尝试在CTE中使用它,但仍然无法让它返回
我在下面使用的代码:
SELECT TOP (2)
cbc.StorePartnerCustConfigID,
p.CustID,
cbc.ConfigID,
cbc.EffectiveDate,
ROW_NUMBER() OVER (ORDER BY cbc.StorePartnerID DESC) AS RowNum
FROM [DB_User].[dbo].[P1ASellers] p
INNER JOIN [ACA].dbo.tblConfig_StorePartnerConfig BP
ON BP.EntityID=CAST(p.CustID AS VARCHAR)
INNER JOIN [ACA].dbo.tblConfig_StorePartner CBP
ON CBP.StorePartnerID=BP.StorePartnerID
INNER JOIN [ACA].dbo.tblConfig_StorePartnerCustConfig CBC
ON CBP.StorePartnerID=CBC.StorePartnerID
AND cbc.ProcessConfigID IN (1,2,3,4)
INNER JOIN [ACA].dbo.tblConfig_StorePartnerCustConfig CBC2
ON CBC.StorePartnerID=CBC2.StorePartnerID
AND cbc2.ConfigID IN (1,2,3,4) where p.CustID=55555 <-need to remove the
where
ORDER BY cbc.StorePartnerID DESC
查询结果 StorePartnerCustConfigID CustID ConfigID EffectiveDate RowNum 15031 55555 4 2015-06-25 1 15032 55555 1 2015-06-25 2
删除where子句后我实际得到的内容: StorePartnerCustConfigID CustID ConfigID EffectiveDate RowNum 68995 89566 2 2011-03-02 1 68996 89566 1 2011-03-02 2
删除where子句后我的期望: StorePartnerCustConfigID CustID ConfigID EffectiveDate RowNum 15031 55555 4 2015-06-25 1 15032 55555 1 2015-06-25 2 64584 65486 2 2013-04-16 1 64585 65486 1 2013-04-16 2 等等.......
非常感谢任何输入,谢谢!
答案 0 :(得分:0)
我认为您正在寻找每位客户的前2名记录,您可以通过以下方式获取:
SELECT TOP (2) with ties
cbc.StorePartnerCustConfigID,
p.CustID,
cbc.ConfigID,
cbc.EffectiveDate,
ROW_NUMBER() OVER (ORDER BY cbc.StorePartnerID DESC) AS RowNum
FROM [DB_User].[dbo].[P1ASellers] p
INNER JOIN [ACA].dbo.tblConfig_StorePartnerConfig BP
ON BP.EntityID=CAST(p.CustID AS VARCHAR)
INNER JOIN [ACA].dbo.tblConfig_StorePartner CBP
ON CBP.StorePartnerID=BP.StorePartnerID
INNER JOIN [ACA].dbo.tblConfig_StorePartnerCustConfig CBC
ON CBP.StorePartnerID=CBC.StorePartnerID
AND cbc.ProcessConfigID IN (1,2,3,4)
INNER JOIN [ACA].dbo.tblConfig_StorePartnerCustConfig CBC2
ON CBC.StorePartnerID=CBC2.StorePartnerID
AND cbc2.ConfigID IN (1,2,3,4)
ORDER (row_number() over(partition by p.CustId Order BY cbc.StorePartnerID DESC-1)/2 +1 )