You are here: Re: Min() query - 5th level optimization « MsSQL Server « IT news, forums, messages
Re: Min() query - 5th level optimization

Posted by Erland Sommarskog on 10/23/07 21:40

Chris H (chollstein@broadreachpartnersinc.com) writes:
> I'm pulling multiple campaigns associated with companies so that I
> have a result set with company name, campaign1, campaign2, campaign3,
> campaign4, campaign5 where the campaigns are listed in alpha order (by
> campaign_code) and each campaign column includes only the one campaign
> (or null). When I got to the 5th level of MIN's, the query seemed to
> expand way beyond what was required for the 4th level join and I
> believe there's "bloat" in the expression. The query works as is, but
> I was wondering if anyone has a suggestion for optimizing? I tried to
> retain the tabulation when I pasted from TOAD, but had to do some
> cleanup anyways so sorry if I didn't get it exactly.

Since I don't have your tables, I cannot write a query for them. But here
is an example for the Orders table in the Northwind database that lists
the first five orders for each customer, and in order.

WITH numbered (CustomerID, OrderID, rn) AS (
SELECT CustomerID, OrderID,
row_number() OVER(PARTITION BY CustomerID ORDER BY OrderID)
FROM Orders
)
SELECT CustomerID,
MIN(CASE rn WHEN 1 THEN OrderID END),
MIN(CASE rn WHEN 2 THEN OrderID END),
MIN(CASE rn WHEN 3 THEN OrderID END),
MIN(CASE rn WHEN 4 THEN OrderID END),
MIN(CASE rn WHEN 5 THEN OrderID END)
FROM numbered
GROUP BY CustomerID
ORDER BY CustomerID

This solution requires SQL 2005, using a Common Table Expression and
the row_number() function.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация