Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Another SQL puzzle...
Message
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01444497
Message ID:
01444554
Views:
41
This solution is worse comparing with my original solution in terms of performance.
-- Test query
ALTER PROCEDURE [dbo].[GetTopNVendors_TopNProducts_CrossApply] 

@TopVendorCount int =5 , 
@TopProductCount int =3, 
@StartDate date ='01-01-2002',
@EndDate date = '12-31-2004' 
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
-- read 3 tables from AdventureWorks - Purchasing.PurchaseOrderHeader, 
-- Purchasing.PurchaseOrderDetail,and Production.Product
--- Retrieve the top X vendors based on $$$ (PurchaseOrderHeader.TotalDue)
--- For each of the top X vendors, retrieve the top Y products based on $$$ (PurchaseOrderDetail.LineTotal)
--- The proc should accept four parameters: the topcount number of vendors, 
--  topcount number of products, and a start/end date range (for the order date)
--- use Dense Ranking

;with cte_TopVendors as (select * from (
select *, DENSE_RANK() over (order by [TotalDue] DESC) as Rank from 
(SELECT OH.[PurchaseOrderID],   
      OH.VendorID, 
      V.Name as [Vendor], SUM(OH.[TotalDue]) over (PARTITION by OH.VendorID) as [TotalDue]   
  FROM [AdventureWorks].[Purchasing].[PurchaseOrderHeader] OH 
       inner join Purchasing.Vendor V on OH.VendorID = V.VendorID 
       where OrderDate between @StartDate and @EndDate ) TV) Y where Rank <= @TopVendorCount),
     TopVendors as (select VendorID, Vendor, TotalDue, Rank from cte_TopVendors group by VendorID, Vendor, TotalDue, Rank)  
       
select V.[Vendor], V.[TotalDue], V.Rank, TP.Product, TP.ProductTotalDue from  TopVendors V      
CROSS APPLY (select top (@TopProductCount) with ties P.Name as [Product], c.VendorID, SUM(POD.[LineTotal]) as ProductTotalDue     
  FROM [AdventureWorks].[Purchasing].[PurchaseOrderDetail] POD 
  inner join cte_TopVendors c on POD.[PurchaseOrderID] = c.[PurchaseOrderID]
  inner join Production.Product P on POD.ProductID = P.ProductID
  WHERE  c.VendorID = V.VendorID 
  GROUP BY c.VendorID, P.Name  ORDER BY SUM(POD.[LineTotal]) DESC) TP 
  order by V.Rank, ProductTotalDue DESC      
  

 end   


GO

--set statistics time on
set statistics io on
print 'Without CROSS APPLY'
exec [dbo].[GetTopNVendors_TopNProducts] @TopVendorCount =5 , @TopProductCount =3, 
@StartDate ='01-01-2002', @EndDate = '12-31-2004'
print 'WITH CROSS APPLY'
exec [dbo].[GetTopNVendors_TopNProducts_CrossApply] @TopVendorCount =5 , @TopProductCount =3, 
@StartDate ='01-01-2002', @EndDate = '12-31-2004'
set statistics io off
--set statistics time off
If it's not broken, fix it until it is.


My Blog
Previous
Reply
Map
View

Click here to load this message in the networking platform