Question

help speeding up code

Asked by: gary_j

I'm having a tough time speeding up some code.  My task is to find the top 50 customers (within some defined time parameters) out of about 3500 customers in the customer table.  The order date and customer number are stored in a header file (currently 50,000 records and growing) and the sales detail is stored in a detail file (311,000 records).  The tables are not designed or populated by me; I'm just trying to get the information out.

i use an array to accumulate the information, then store that in a table by customer so that it can be recalled on next startup

The array consists of elements 1 (current year), 2 (last year), 3 (last ytd), 4 thru 15 (Jan - Dec this year)

"Top 50" is based on current year sales

This is written in VB6 against a SQL Server database

This code takes 14 minutes to run, which seems like too much -- is there another method of attack that would reduce the processing time?

Private Sub cmdRefresh_Click()
    Dim rs1 As ADODB.Recordset
    Dim rs2 As ADODB.Recordset
    Dim rs3 As ADODB.Recordset
    Const strFr10 As String = "##,###,##0"
    Const strfr9 As String = "#,###,##0"
    Dim lngJan1TY As Long
    Dim lngJan1LY As Long
    Dim lngDec31TY As Long
    Dim lngDec31LY As Long
    Dim lngTDLY As Long
    Dim dblAmt As Double
    Dim alngFileAmt(1 To 15) As Long
    Dim i As Integer
    Dim strSql As String
   
    Debug.Print "start " & CStr(Now)
   
    Me.MousePointer = vbHourglass
    cmdRefresh.Enabled = False
    flx1.Visible = False
    flx1.Enabled = False
    flx1.Rows = 1
   
    Call getConn   'my connection string is         "Provider=SQLOLEDB.1;" & _
                                                                    "Persist Security Info=False;" & _
                                                                    "User ID=" & strUserId & ";" & _
                                                                    "Password=" & strPW & ";" & _
                                                                    "Initial Catalog=" & strCatalog & ";" & _
                                                                    "Data Source=" & strDataSource

   
    'update parameters
    g_cnnActive.Execute "UPDATE top50sls_fli SET lr_date = " & _
        Format(Date, "YYYYMMDD") & ", lr_yr = '" & lstYr.List(lstYr.ListIndex) & "'"
    txtInfo(0).Text = Format(Date, "MM/DD/YYYY")
    txtInfo(1).Text = lstYr.List(lstYr.ListIndex)
   
    Set rs1 = New ADODB.Recordset
    Set rs2 = New ADODB.Recordset
    Set rs3 = New ADODB.Recordset
   
    Set rs1.ActiveConnection = g_cnnActive
    Set rs2.ActiveConnection = g_cnnActive
    Set rs3.ActiveConnection = g_cnnActive
   
    If gbolSuppRefresh = False Then
        'get dates
        lngJan1TY = lstYr.List(lstYr.ListIndex) + "0101" 'January 1 of the "current" year
        lngJan1LY = CStr(CLng(lstYr.List(lstYr.ListIndex) - 1)) + "0101" 'January 1 of the "previous" year
        lngDec31TY = lstYr.List(lstYr.ListIndex) + "1231" 'December 31 of the "current" year
        lngDec31LY = CStr(CLng(lstYr.List(lstYr.ListIndex) - 1)) + "1231" 'December 31 of the previous" year
        lngTDLY = CStr(Year(Date) - 1) + CStr(Month(Date)) + CStr(Day(Date))
        'clear file
        g_cnnActive.Execute "TRUNCATE TABLE top50act_fli"
       
        'get new information into the file
       
        rs1.Open "SELECT customer FROM customer_table ORDER BY customer"
       
        Do While Not rs1.EOF
            stb1.Panels(1).Text = " " & Right(rs1.Fields("customer"), 5) & "  "
            'clear array
            Erase alngFileAmt
           
            rs2.Open "SELECT type,orig_type,order_num,order_dt FROM hdrhstTable WHERE order_dt " & _
                "BETWEEN " & lngJan1LY & " And " & lngDec31TY & " And customer = '" & _
                rs1.Fields("customer").Value & "'"
           
            Do While Not rs2.EOF
                dblAmt = 0
                If rs2.Fields("orig_type").Value = "C" Then
                    rs3.Open "SELECT SUM(ship_qty * price) [Amt] FROM dethstTable WHERE " & _
                        "type = '" & rs2.Fields("type").Value & "' And order_num = '" & _
                        rs2.Fields("order_num").Value & "'"
                   
                    If Not IsNull(rs3.Fields("Amt").Value) Then
                        dblAmt = rs3.Fields("Amt").Value
                    End If
                   
                    rs3.Close
                Else
                    rs3.Open "SELECT SUM(order_qty * price) [Amt] FROM dethstTable WHERE " & _
                        "type = '" & rs2.Fields("type").Value & "' And order_num = '" & _
                        rs2.Fields("order_num").Value & "'"
                   
                    If Not IsNull(rs3.Fields("Amt").Value) Then
                        dblAmt = rs3.Fields("Amt").Value
                    End If
                   
                    rs3.Close
                End If
               
                If rs2.Fields("order_dt").Value >= lngJan1TY And _
                            rs2.Fields("order_dt").Value <= lngDec31TY Then
                    alngFileAmt(1) = alngFileAmt(1) + dblAmt
                   
                    'now get the monthly amount in there
                    alngFileAmt(CInt(Mid(rs2.Fields("order_dt").Value, 5, 2)) + 3) = _
                        alngFileAmt(CInt(Mid(rs2.Fields("order_dt").Value, 5, 2)) + 3) + dblAmt
                End If
               
                If rs2.Fields("order_dt").Value >= lngJan1LY And _
                            rs2.Fields("order_dt").Value <= lngDec31LY Then
                    alngFileAmt(2) = alngFileAmt(2) + dblAmt
                End If
               
                If rs2.Fields("order_dt").Value >= lngJan1LY And _
                            rs2.Fields("order_dt").Value <= lngTDLY Then
                    alngFileAmt(3) = alngFileAmt(3) + dblAmt
                End If

                rs2.MoveNext
            Loop
           
            rs2.Close
           
            'file the information about this customer
            '   (if there are any sales this year)
            If alngFileAmt(1) > 0 Then
                strSql = "INSERT INTO top50act_fli (customer,tot_cy,tot_ly,tot_ly_ytd," & _
                    "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dem) VALUES ('" & _
                    Right(rs1.Fields("customer").Value, 5) & "'"
               
                For i = 1 To 15
                    strSql = strSql & "," & alngFileAmt(i)
                Next 'i
               
                strSql = strSql & ")"
                g_cnnActive.Execute strSql
            End If
            DoEvents
           
            rs1.MoveNext
        Loop
        rs1.Close
    End If
   
    'put information into the grid
    rs1.Open "SELECT customer,tot_cy,tot_ly,tot_ly_ytd,jan,feb,mar,apr,may,jun,jul,aug," & _
        "sep,oct,nov,dem FROM top50act_fli ORDER BY tot_cy DESC"
       
    Do While Not rs1.EOF
        With flx1
            .Rows = .Rows + 1
            .Row = .Rows - 1
            .Col = 0
            .Text = rs1.Fields("customer").Value
            .Col = 1
            .Text = padLeft(Format(rs1.Fields("tot_cy").Value, strFr10), 10)
            .Col = 2
            .Text = padLeft(Format(rs1.Fields("tot_ly").Value, strFr10), 10)
            .Col = 3
            .Text = padLeft(Format(rs1.Fields("tot_ly_ytd").Value, strFr10), 10)
            .Col = 4
            .Text = padLeft(Format(rs1.Fields("jan").Value, strfr9), 9)
            .Col = 5
            .Text = padLeft(Format(rs1.Fields("feb").Value, strfr9), 9)
            .Col = 6
            .Text = padLeft(Format(rs1.Fields("mar").Value, strfr9), 9)
            .Col = 7
            .Text = padLeft(Format(rs1.Fields("apr").Value, strfr9), 9)
            .Col = 8
            .Text = padLeft(Format(rs1.Fields("may").Value, strfr9), 9)
            .Col = 9
            .Text = padLeft(Format(rs1.Fields("jun").Value, strfr9), 9)
            .Col = 10
            .Text = padLeft(Format(rs1.Fields("jul").Value, strfr9), 9)
            .Col = 11
            .Text = padLeft(Format(rs1.Fields("aug").Value, strfr9), 9)
            .Col = 12
            .Text = padLeft(Format(rs1.Fields("sep").Value, strfr9), 9)
            .Col = 13
            .Text = padLeft(Format(rs1.Fields("oct").Value, strfr9), 9)
            .Col = 14
            .Text = padLeft(Format(rs1.Fields("nov").Value, strfr9), 9)
            .Col = 15
            .Text = padLeft(Format(rs1.Fields("dem").Value, strfr9), 9)
        End With
       
        If flx1.Rows = 51 Then
            Exit Do
        End If
       
        rs1.MoveNext
    Loop
   
    rs1.Close
   
    Set rs1.ActiveConnection = Nothing
    Set rs2.ActiveConnection = Nothing
    Set rs3.ActiveConnection = Nothing
   
    Set rs1 = Nothing
    Set rs2 = Nothing
    Set rs3 = Nothing
   
    Call closeConn
   
    flx1.Enabled = True
    flx1.Visible = True
    cmdRefresh.Enabled = True
    stb1.Panels(1).Text = ""
    Me.MousePointer = vbDefault
   
    Debug.Print "end " & CStr(Now)
End Sub

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-12-14 at 07:08:25ID21241844
Tags

padleft

,

vb6

Topic

VB Database Programming

Participating Experts
5
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. const
    I have trouble to initialize a const in class,where should I initialize it ? A sample is ideal. It's very urgent,please hurry up. Thanks.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: SQL_StuPosted on 2004-12-14 at 07:23:52ID: 12820147

9 times out of 10, the speed any code runs based on SQL results depends on the setup of the database, rather than the coding.

Having said that, a couple of suggestions are:

Use a stored procedure in SQL to populate your top50 table.

How about storing the top 50 records in an array, rather than an SQL table?

Stu

 

by: g0rathPosted on 2004-12-14 at 11:01:16ID: 12822682

If you use a table then recreate it....
I've got a process that takes a 16,000 record table linked to another 8,000 record table, and does some statistics for it, now I've optimized my indexes for this, and its fast, but it was taking 90 seconds through crystal report.

I took a stored procedures and "cached" the data....but stored the last time I cached the data.
Every thing the stored procedures runs, it checks the date of the cache, if it's recent then it just runs the query against my "cache" table, otherwise it recreates the cache table.

Now it takes 45seconds worst case scenario, but 1 second best case.

Watch the queries, use the SQL Analyzer and watch the execution plan. Optimize based up that. And also if you don't need to know the Top50 Real time, then cache it.

 

by: aikimarkPosted on 2004-12-14 at 11:36:45ID: 12823100

You can easily find the top 50 performers with a query that looks something like this:

"SELECT Top 50 customer_table.customer,
( Select SUM(dethstTable.ship_qty * dethstTable.price) FROM dethstTable WHERE dethstTable.customer =   customer_table.customer And type = 'C' And order_dt BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "' ) [ShippedAmt] ,
( Select SUM(dethstTable.order_qty * dethstTable.price) FROM dethstTable WHERE dethstTable.customer =   customer_table.customer And type <> 'C' And order_dt BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "') [OrderedAmt],
 [ShippedAmt] + [OrderedAmt] [TotalAmt]
FROM customer_table ORDER BY TotalAmt Desc"
================================
Note: This is just a start.  The months can be similarly summed in this query.

 

by: gary_jPosted on 2004-12-14 at 14:44:04ID: 12825062

aikimark:

thank you, but I'm having one problem with the select statement,

SELECT Top 50 customer_table.customer,
( Select SUM(dethstTable.ship_qty * dethstTable.price) FROM dethstTable WHERE dethstTable.customer =   customer_table.customer And type = 'C' And order_dt BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "' ) [ShippedAmt] ,
( Select SUM(dethstTable.order_qty * dethstTable.price) FROM dethstTable WHERE dethstTable.customer =   customer_table.customer And type <> 'C' And order_dt BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "') [OrderedAmt],
 [ShippedAmt] + [OrderedAmt] [TotalAmt]
FROM customer_table ORDER BY TotalAmt Desc

The columns "type" and "order_dt"  actually comes from a third table: hdrhstTable
I tried, but couldn't figure out how to join this third table into the query

 

by: aikimarkPosted on 2004-12-14 at 15:42:16ID: 12825543

They are joined by their order_num columns.  

These table names are very similar and I missed this difference when reading your code.

 

by: gary_jPosted on 2004-12-15 at 06:54:58ID: 12830397

Hi again and thanks again aikimark.

I changed the query to this

SELECT Top 50 customer_table.customer,
( Select SUM(dethstTable.ship_qty * dethstTable.price) FROM dethstTable
,hdrhsttable                                <------------ change
 WHERE dethstTable.customer =   customer_table.customer And
dethsttable.type = hdrhsttable.type And dethsttable.order_num = hdrhsttable.ord_num       <--------- change
 and hdrhsttable.orig_type = 'C' And hdrhsttable.order_dt              <----------- change
 BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "' ) [ShippedAmt] ,
( Select SUM(dethstTable.order_qty * dethstTable.price) FROM dethstTable
,hdrhsttable                              <--------------- change
 WHERE dethstTable.customer =   customer_table.customer And
dethsttable.type = hdrhsttable.type And dethsttable.order_num = hdrhsttable.ord_num  <--------------- change
 and hdrhsttable.orig_type <> 'C' And hdrhsttable.order_dt    <-------------- change
 BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "') [OrderedAmt],
 [OrderedAmt] - [ShippedAmt] [TotalAmt]         <-------------formula change
FROM customer_table ORDER BY TotalAmt Desc

and now the only problem seems to be that it doesn't like the aliases:

Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'OrderedAmt'.
Server: Msg 207, Level 16, State 1, Line 1
Invalid column name 'ShippedAmt'.


Thanks again for your help!!

 

by: LowfatspreadPosted on 2004-12-15 at 09:04:29ID: 12832079

couldn't see anything basically wrong in the above but probably better written as

Select Top 50 x.*
      , [OrderedAmt] - [ShippedAmt] as [TotalAmt]
  from (
SELECT CT.customer,
      ,sum(case when hdr.orig_type = 'c' then HT.ship_qty * HT.price
             else null end) as [shippedAmt]
      ,SUM(case when hdr.orig_type = 'c' then null
             else HT.order_qty * HT.price end) as [OrderedAmt]
  FROM customer_table as CT
 Inner Join dethstTable as HT
    on HT.customer =   CT.customer
 Inner Join (select * from hdrhsttable
             Where HDR.order_dt  
                  BETWEEN '" & lngJan1LY & "' And '" & lngDec31TY & "')
       as hdr                      
   on HT.type = HDR.type
  And HT.order_num = HDR.ord_num
Group by CT.Customer
   ) as x
ORDER BY TotalAmt Desc



you can add more

sum(case when ...)

constructs to obtain the values for the month information you want...


your basic error was to "LOOP" /"CURSOR"  through the data in the VB app....
for what is a simple set of SQL selections....


you should put this code into a stored procedure and let the database handle the summarisation for you...

you may need to look at indexes on the tables but the basic three table join seems simple enough,
and with a reasonably machine i'd have though you'd get a decent response given your small number of rows involved
only 50K and 300K...


hth    

 

by: gary_jPosted on 2004-12-15 at 09:15:35ID: 12832223

Thank you both for your help, but now it's gotten even more complicated.  My problem is that I'm not a SQL guy (although I'm being forced by problems like this to get there!), so I'm forced into these loops because I don't know how to extract it in complex sql queries.

Anyhow, now I have found out that the history header can have multiple records for the same order.  My task, of course is to extract the detail for any given order.

So bottom line is that for each customer in the customer table, I need the DISTINCT set of header records from the order history header table, and then to summarize the correct quantity (based on original type from the history header table) * the price, both of which are stored in the history detail table and match up to the history header table based on order type (not original order type) and order number.  Then of course, I need to dump these totals into varioius "buckets" based on the order date (stored in the history header records).

So the new twist is the 'DISTINCT' problem ...

Thanks very much for your help.

 

by: aikimarkPosted on 2004-12-15 at 09:44:41ID: 12832551

thanks lowfatspread for supplying the missing the "AS" for the alias.

======================
gary_j,

Are there any differences between the multiple header for the different order items?  We are using the header table to get the type of order for purposes of calculating the ship vs. ordered amount value.  Duplicates will certainly mess up these calculations.

My recommendation would be to delete these duplicate header rows before you start.  If you can't do that or the multiple header rows are different, then we need to know the relationship between multiple header rows and the order item rows.

If we can safely remove the need for the type, then we can remove the header table from the query.
Example:
Sum(ship_qty * price + order_qty * price) As [AMT]

or
Sum((ship_qty * price) + ((order_qty-ship_qty) * price)) As [AMT]


This assumes that the fields are not Null.  If they can contain Null values, then we will need to translate Null values into 0 in the query.  You might use either the Case or NullIf statements for this.

 

by: LowfatspreadPosted on 2004-12-15 at 09:51:43ID: 12832632

Yes please explain how you'd chose the appropriate Hdrhst entry...

if will help if you can provide the table layouts and relationship details....


you DBA will be able to provide you with a script which will show the DDL for each table...

 

by: gary_jPosted on 2004-12-15 at 10:04:09ID: 12832742

Thanks again for all your help here!

Here's how the tables relate with the needed information

header table will always have the same key information, no matter how many entries are involved:
            order type, order number, order date, original order type, customer number

this relates to the detail table simply by order type + order number (note: not ORIGINAL order type)

in the detail table, there is quantity ordered, quantity to ship, and unit_price.
If the original order type in the header table is 'C', then I need quantity ordered, otherwise
       I need quantity to ship (I had this backwards above)

We could actually leave the customer table out of the equation, because customer number is stored in the header table

So what I need is for each distinct customer mentioned in the header table, each distinct order that has an order date between (in this case)  20030101 and 20041231

From that I need to get the amount for the order, which is the sum of the quantity * the price for all rows in the detail table.  If the header table has an original order type of 'C' it's handled differently than if not (per above)

Then I need to put these numbers in one or more of 15 buckets:
         This ytd (20040101 to 20041231)
         Last ytd (20030101 to 20031231)
         Last year through this date (20030101 to 20031215)
         Current year monthly buckets

I can not delete any rows in either table (it's not my database).
Nulls should not be an issue -- they're not allowed in any of our subject columns

Thanks again!

 

by: kishore3576Posted on 2004-12-20 at 09:06:12ID: 12868382

I generally prefer using temporary tables in such cases.

sql = "select a.order_type, a.Order_number, a.CustomerCode, sum(b.qtyOrdered * b.unit_price) as Val into tempOrdValC from Header a, Detail b group by a.order_number, a.order_type, a.CustomerCode where a.OrderDate between 20040101 and 20041231 and a.OriginalOrderType = 'C'"
conn.execute sql

sql = "select a.order_type, a.Order_number, a.CustomerCode, sum(b.qtyOrdered * b.unit_price) as Val into tempOrdValNotC from Header a, Detail b group by a.order_number, a.order_type, a.CustomerCode where a.OrderDate between 20040101 and 20041231 and a.OriginalOrderType <> 'C'"
conn.execute sql

sql = "select * into tempOrdVal from tempOrdValC"
conn.execute sql

sql = "insert into tempOrdVal select * from tempOrdValNotC"
Conn.execute sql

Now you can select the top 50 from tempOrdVal

Just remember to drop these temporary tables at the end of all coding

Hope I am helpful

 

by: aikimarkPosted on 2005-02-27 at 12:48:14ID: 13415666

gary_j,

Where do we stand with this problem?  It seems to have dropped off our radar and is close to being an abandoned question.

 

by: gary_jPosted on 2005-02-28 at 05:39:38ID: 13419336

Where we stand is that I haven't had a chance to try to "improve" the code that's in place.  It's in my "to do" list, just can't get there.  I'll try to take a look this week, and award some points based on effort, even if I can't solve my problem.  Thanks.

 

by: aikimarkPosted on 2005-02-28 at 06:26:41ID: 13419705

Don't rush to award points at the expense of solving your problem.  We are here to help solve problems.  This one is just taking a while to understand and resolve.

For the Current Year Monthly Buckets, I'd recommend creating 12 columns (static) in your query, rather than trying to create only the columns up to the current month.  Sufficient criteria will make the sums of monthly buckets beyond the current month = 0.

 

by: gary_jPosted on 2005-03-15 at 13:12:57ID: 13549026

As luck would have it, this project changed dramatically before I got a chance to implement any of the solutions.  I am awarding points to all that tried to help.

Thank you all.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...