Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


sum every two number combination


sum every two number combination

Author
Message
Amy.G
Amy.G
SSC-Enthusiastic
SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)

Group: General Forum Members
Points: 107 Visits: 290
Let's say your coworker gave you the results of a query, and noted he/she did not include SalesOrderID numbers 43674 and 44295. However, you run that query: (from AdventureWorks)

SELECT [SalesOrderID]
, a.City
,[TotalDue]
FROM [AdventureWorks].[Sales].[SalesOrderHeader] s
INNER JOIN AdventureWorks.Person.Address a
ON s.BillToAddressID = a.AddressID
WHERE City = 'Ottawa'
AND SalesOrderID NOT IN ('43674','44295')

And find that you're grand total for orders = $98689.28, whereas the results the coworker sent has as grand total in sales of $109276.67. So you know he/she made a mistake and excluded the wrong two SalesOrderIDs. Now, obviously, the solution is to call and ask them to open the query and verify the excuded IDs. That's exactly what I did, and issue is resolved. But I got it into my head that it would be cool to be able to somehow figure out the two excluded IDs by summing all two number combinations until you found the sum that matched the difference.

This is more of a pet project or brain teaser I've given myself, but I'm not getting very far. A gentle nudge in the right direction would be nice. ;-)
patrickmcginnis59
patrickmcginnis59
SSC-Addicted
SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)

Group: General Forum Members
Points: 431 Visits: 2333
A wild guess just for fun! Cue all smarter folks to line up and show how inefficient this query is!


SELECT TAB1.SalesOrderId AS ID1,
TAB1.TotalDue AS DUE1,
TAB2.SalesOrderId AS ID2,
TAB2.TotalDue AS DUE2
FROM SALESTABLE TAB1
CROSS JOIN
SALESTABLE TAB2
WHERE TAB1.SalesOrderID <> TAB2.SalesOrderID AND
TAB1.TotalDue + TAB2.Totaldue = @SPECIFIED_DIFFERENCE


Amy.G
Amy.G
SSC-Enthusiastic
SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)

Group: General Forum Members
Points: 107 Visits: 290
You know, it worked. It tool 3.58 minutes, but it worked. :-)
Lynn Pettis
Lynn Pettis
SSC-Insane
SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)

Group: General Forum Members
Points: 24278 Visits: 37987
Can TotalDue every be less than 0?

Cool
Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
Luis Cazares
Luis Cazares
SSCrazy Eights
SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)

Group: General Forum Members
Points: 8582 Visits: 18157
I don't have anything to test with, but I believe this could be better.
However, the problem is that it's still using a cartesian product to obtain the result.

SELECT TAB1.SalesOrderId AS ID1, 
TAB1.TotalDue AS DUE1,
TAB2.SalesOrderId AS ID2,
TAB2.TotalDue AS DUE2
FROM SALESTABLE TAB1
JOIN SALESTABLE TAB2 ON TAB1.SalesOrderID < TAB2.SalesOrderID --Avoid half of the rows.
WHERE TAB1.TotalDue < @SPECIFIED_DIFFERENCE --This are useless unless you have negatives.
AND TAB2.TotalDue < @SPECIFIED_DIFFERENCE --Same as above.
AND TAB1.TotalDue + TAB2.Totaldue = @SPECIFIED_DIFFERENCE



I'm not sure if the conditions added will help but I'm sure the condition for the join must help the performance.


Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?


How to post data/code on a forum to get the best help: Option 1 / Option 2
Amy.G
Amy.G
SSC-Enthusiastic
SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)SSC-Enthusiastic (107 reputation)

Group: General Forum Members
Points: 107 Visits: 290
Lynn Pettis (9/24/2012)
Can TotalDue every be less than 0?


No. And there are no nulls.
Lynn Pettis
Lynn Pettis
SSC-Insane
SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)SSC-Insane (24K reputation)

Group: General Forum Members
Points: 24278 Visits: 37987
Luis Cazares (9/24/2012)
I don't have anything to test with, but I believe this could be better.
However, the problem is that it's still using a cartesian product to obtain the result.

SELECT TAB1.SalesOrderId AS ID1, 
TAB1.TotalDue AS DUE1,
TAB2.SalesOrderId AS ID2,
TAB2.TotalDue AS DUE2
FROM SALESTABLE TAB1
JOIN SALESTABLE TAB2 ON TAB1.SalesOrderID < TAB2.SalesOrderID --Avoid half of the rows.
WHERE TAB1.TotalDue < @SPECIFIED_DIFFERENCE --This are useless unless you have negatives.
AND TAB2.TotalDue < @SPECIFIED_DIFFERENCE --Same as above.
AND TAB1.TotalDue + TAB2.Totaldue = @SPECIFIED_DIFFERENCE



I'm not sure if the conditions added will help but I'm sure the condition for the join must help the performance.


What you have here is what I was thinking. If the total due for each order can not be less than zero, then it makes sense to restrict the testing to orders where the total due for each order is less than or equal to the total difference. If you could have a negative total, then this check would not be worthwhile.

Cool
Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
patrickmcginnis59
patrickmcginnis59
SSC-Addicted
SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)SSC-Addicted (431 reputation)

Group: General Forum Members
Points: 431 Visits: 2333
Or we could put an index on the totaldue column ;-)


SELECT TAB1.SalesOrderId AS ID1,
TAB1.TotalDue AS DUE1,
TAB2.SalesOrderId AS ID2,
TAB2.TotalDue AS DUE2
FROM SALESTABLE TAB1
JOIN
SALESTABLE TAB2
ON TAB1.Totaldue = @SPECIFIED_DIFFERENCE - TAB2.Totaldue


Sean Lange
Sean Lange
SSCoach
SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)

Group: General Forum Members
Points: 16669 Visits: 17030
And of course if the exact rows matter this can get a LOT more challenging because there may be more than 1 pair where the sum is the total you are looking for.

_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)

Group: General Forum Members
Points: 4291 Visits: 6431
Sean Lange (9/24/2012)
And of course if the exact rows matter this can get a LOT more challenging because there may be more than 1 pair where the sum is the total you are looking for.


I can do that! And I can examine triplet combinations (or deeper) as well!


DECLARE @Orders Table
(OrderID VARCHAR(4), Amount MONEY)

INSERT INTO @Orders
SELECT 2122, 5400
UNION ALL SELECT '2123', 5500
UNION ALL SELECT '2124', 1500
UNION ALL SELECT '2125', 5700
UNION ALL SELECT '2126', 4500
UNION ALL SELECT '2126', 1500
UNION ALL SELECT '2127', 5200
UNION ALL SELECT '2129', 1000

DECLARE @Amount MONEY = 7000

;WITH UNIQUEnTuples (n, Tuples, Amount) AS (
SELECT 1
-- Add brackets around the OrderID to make later string comparison unique
, CAST('[' + OrderID + ']' AS VARCHAR(max)) COLLATE Latin1_General_BIN
,Amount
FROM @Orders
UNION ALL
SELECT 1 + n.n, a.OrderID + n.Tuples, n.Amount + t.Amount
FROM @Orders t
CROSS APPLY (
SELECT '[' + t.OrderID + ']') a(OrderID)
JOIN UNIQUEnTuples n ON a.OrderID < n.Tuples
WHERE CHARINDEX(a.OrderID, n.Tuples) = 0 AND n < 3 AND
n.Amount + t.Amount <= @Amount
)
SELECT *
FROM UNIQUEnTuples
WHERE Amount = @Amount -- The sum you're intereseted in identifying




For an explanation of this approach, you can take a look at this article: http://www.sqlservercentral.com/articles/sql+n-Tuples/89809/

I've found that the COLLATE I added improves performance slightly. You can modify n < 3 to account for the depth of nTuples you want to examine.

Edit: Added the @Amount variable so I could use it to limit the rows examined in the recursive leg of the rCTE (potentially improves performance).


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search