edgarmtze
edgarmtze

Reputation: 25048

get specific rows of table given a rule SQL Server 2008

I have a table like:

ID   NAME     VAL
----------------------
1   a1*a1   90052
2   a1*a2   236
3   a1*a3   56
4   a1*a4   6072
5   a1*a5   1004
6   a2*a2   4576
7   a2*a3   724
8   a2*a4   230
9   a2*a5   679
10  a3*a3   5
11  a3*a4   644
12  a3*a5   23423
13  a4*a4   42354
14  a4*a5   10199
15  a5*a5   10279

Given a number given S = 5, I want to query the rows wth id: 1,6,10,13,15 they are a1*a1,a2*a2,a3*a3,a4*a4 and a5*a5

I would like something like:

INSERT #NEW_TABLE (ID,NAME,Value) (
SELECT ordinal, NAME, VAL FROM myTable where id = 1,6,10,13,15)

to get

  ID   NAME     VAL
    ----------------------
    1   a1*a1   90052
    2   a2*a2   4576
    3   a3*a3   5
    4   a4*a4   42354
    5   a5*a5   10279

Is there a way to do this for any given S, Maybe wth dynamic sql?

I was getting the formula and I got this:

S=5

ID     formula
1      1
6      1+S
10     1+S+ (S-1)
13     1+S+ (S-1) + (S-2)
15     1+S+ (S-1) + (S-2) + (S-3)

Is there a way to do this inside a case or a while loop?

Upvotes: 1

Views: 880

Answers (1)

JNK
JNK

Reputation: 65157

This worked in testing.

You can just inner join on @Tab to limit your results. You probably also want to add some traps for values below 3, which I haven't done.

The basic process is

  • Declare your @s value
  • Insert the first two rows since they will always be the same
  • In a loop, insert one row at a time with an incrementing difference
  • Loop exits once it has run @s-2 times

Try:

DECLARE @Tab Table (id INT)

DECLARE @S int = 5,
        @ct int

DECLARE @cur int = (1 + @S)

INSERT INTO @Tab SELECT 1
INSERT INTO @Tab SELECT (1 + @S)

SET @ct = 1

WHILE @ct <= @S - 2
BEGIN

    SET @cur = @cur + (@S - @ct)

    INSERT INTO @Tab SELECT @cur

    SET @ct = @ct + 1

END

SELECT * FROM @Tab
ORDER BY id

To use this in your query, you can do either:

SELECT ordinal, NAME, VAL 
FROM myTable 
WHERE id IN (SELECT id FROM @Tab)

-- OR

SELECT ordinal, NAME, VAL 
FROM myTable t
INNER JOIN @tab t2
    ON t2.id = t.id

Upvotes: 2

Related Questions