I need to select the top 3 records from a table, but depending on an inline variable from an iteration, occasionally one of those top 3 records should not be selected and should be replaced by the top 4th.
I'm using sql expression in a personal geodatabase with Arc.
So far I have this:
SELECT * FROM MyTable WHERE
[Field1] in(SELECT TOP 3 ([Field1])
FROM MyTable
ORDER BY [Field1] DESC)
AND NOT [Field2] = '%Variable%'
This just selects the top three or the top 2 when [Field2] equals an inline variable. I'm a syntax sql NOOB, but I have a basic understanding of what can be done and that it is probably a simple solution.
Maybe:
If
Count([Field1] in(SELECT TOP 3 ([Field1])
FROM MyTable
ORDER BY [Field1] DESC)
AND NOT [Field2] = '%Variable%') = 3
SELECT * FROM MyTable WHERE
[Field1] in(SELECT TOP 3 ([Field1])
FROM MyTable
ORDER BY [Field1] DESC)
AND NOT [Field2] = '%Variable%'
END
Else
[Field1] in(SELECT TOP 4 ([Field1])
FROM MyTable
ORDER BY [Field1] DESC)
AND NOT [Field2] = '%Variable%'
END
Something like that?
Best Answer
I suggest this:
Example
Let's start with an unordered table:
To get the top 3 but not orange, use this:
That will skip 'orange' and include the 4th item:
If but if you change your variable to
WHERE color_name <> 'blue'
then you get simply the top 3: