If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Excel Sumif Equivalent in SQL?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-26-11, 18:59
imwild124 imwild124 is offline
Registered User
 
Join Date: Jul 2011
Posts: 6
Excel Sumif Equivalent in SQL?

Hello everyone,

I'm trying to put together a piece of code in SQL that is similar to the sumif function in Excel. Basically, what I am trying to do is add the total number of miles that a truck travels on a particular delivery and then categorize that load as "very long" if it is over 500 miles. The problem is that the truck might make multiple stops on a delivery and each line item is an individual stop.

To help explain, I threw together an example below. Basically what I want to do is add up the total delivery miles for each Load ID#. For instance, Load ID# 1 equals a total of 250 miles so it should be ignored. Load ID#2 however equals 1100 miles and should be considered "very Long". My overall goal is to be able to count the total # of "very long" loads.

I'd appreciate any help!



Stop # Load ID # Miles
1 1 100
2 1 50
3 1 100
1 2 300
2 2 400
3 2 400
1 3 10
2 3 15
3 3 20


(This is sort of what I was thinking?)


SELECT
Count(Distinct [Route #])AS Loads
FROM TBL_MasterData
Where
Sum(i.Distance) AS [iRaw_Miles]) >500
GROUP BY
Route #,
Distance

ORDER BY
Route #
Reply With Quote
  #2 (permalink)  
Old 10-27-11, 02:26
it-iss.com it-iss.com is offline
Registered User
 
Join Date: Sep 2009
Location: San Sebastian, Spain
Posts: 620
If you sum up the miles grouped by load, this will give you the total you are looking for. If you want to further filter the resulting group by look at HAVING as follows:

Code:
SELECT
`Load ID #`, SUM(Miles)
FROM TBL_MasterData
GROUP BY `Load ID #`
HAVING SUM(Miles) > 500
__________________
Ronan Cashell
Senior Oracle/MySQL DBA
http://www.it-iss.com
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On