Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
nextaxtion
Yak Posting Veteran
54 Posts |
Posted - 2015-02-08 : 14:46:27
|
hi team, I have a table having single column id and n number of rows and 1 want to know all combination of id's where sum or subtraction of any two id's is equal to 7.id12345691218....so output should be like 2 53 417 10 .......please help. prithvi nath pandey |
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2015-02-08 : 15:24:14
|
Here you go:declare @t table (id int)insert into @t values(1),(2),(3),(4),(5),(6),(9),(10),(12),(17),(18)select * from (select t1.id as t1id, t2.id as t2idfrom @t t1cross join @t t2) twhere t1id + t2id = 7 or t2id - t1id = 7 or t1id - t2id = 7Tara KizerSQL Server MVP since 2007http://weblogs.sqlteam.com/tarad/ |
|
|
bitsmed
Aged Yak Warrior
545 Posts |
Posted - 2015-02-08 : 16:31:57
|
Alternative:select * from yourtable as a inner join yourtable as b on 7 in (a.id+b.id,a.id-b.id,b.id-a.id) |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2015-02-09 : 03:54:16
|
Do you want permutations or combinations?2 55 2or only2 5?? Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA |
|
|
pradeepbliss
Starting Member
28 Posts |
Posted - 2015-02-09 : 05:11:15
|
quote: Originally posted by nextaxtion hi team, I have a table having single column id and n number of rows and 1 want to know all combination of id's where sum or subtraction of any two id's is equal to 7.id12345691218....so output should be like 2 53 417 10 .......please help. prithvi nath pandey
create procedure [dbo].[SP_Addition]asbegindeclare @i intdeclare @j intdeclare @k intselect @k = max(id) from @YourTableNameset @i = 1FirstLoop:if @i <= @kbeginset @j= @i + 1SecondLoop:if @i + @j = 7beginselect @i as 'Col-1',@j as 'Col-2'set @i= @i + 1goto FirstLoopendelsebeginset @j= @j + 1if @j < @kbegingoto SecondLoopendelsegoto ThirdLoopendendThirdLoop:end |
|
|
|
|
|
|
|