我想獲得前5個客戶類型並顯示每個5個客戶類型的數據,餘額(可以是任意數量),我將它們顯示爲「其他客戶類型」。我的問題是,因爲行可能是隨機的,並不能完全被數字整除,那麼在「其他」組中出現的前5位中可能會重複的值超過總銷售額。Top N百分比和最高M百分比Asc
數據也被呈現在SSRS
我的代碼使用TOP PERCENT:
select final.[description], sum(final.YTDSales$) as YTDSales$
FROM(
select top 25 percent pytd2.[Description], sum(pytd2.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt)/@exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN @FStartDate AND @EndDate AND ol.Cono = 1 and ol.VendId IN(@Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD2
group by pytd2.[description]
order by sum(pytd2.YTDSales$) DESC
UNION ALL
select top 75 percent 'Other' as 'description', sum(pytd.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt)/@exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN @FStartDate AND @EndDate AND ol.Cono = 1 and ol.VendId IN(@Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD
group by Ppytd.[description]
order by sum(pytd.YTDSales$)
)final
group by final.[Description]
order by sum(final.YTDSales$) DESC
我不認爲你要與這個取得任何進展 - 但好運氣 – Strawberry
所以你說你要前5的關係?您在查詢中使用最高的25%,那麼這意味着您有20個客戶類型或什麼? – shawnt00
總共有41個客戶類型...但在這個查詢中,我得到32個,因爲其中9個在2016年1月份沒有購買 – BuddingProgrammer