Wednesday, March 28, 2012

Need the logic to get this done without cursors

Suppose in the table below the left column is called intNumber and right column is called strItem.I want to select the rows where the intNumber number appears for the first time(the ones marked with arrows), how do I do it?

for intNumber = 1 what is the logic to choose x rather than y ?

for intNumber = 2 what is the logic to choose z rather than m ?

|||

dilbert1947:

I want to select the rows where the intNumber number appears for the first time

As khtan is asking, what is the logic behind your requirement? SQL Server has no concept of "first" without some kind of data sorting.

Typically what you are asking for could be accomodated by this sort of query, where the non-unique columns(s) are aggregated in some manner:

SELECT intNumber, MIN(strItem) FROM myTable GROUP BY intNumber ORDER BY intNumber

|||

Are you trying to accomplish this from code on a page, or in your SQL data manager? If you are doing this from a page, you could use a function with logic such as:

dataset1 = SELECT DISTINCT id FROM tableName //populates with 1 entry for each different ID</P><P>while(dataset != null){ //loop until out of ID's</P><P>dataset2 = SELECT TOP 1 * FROM tableName WHERE id = dataset1.value; // grab top record for each distinct ID</P><P>//do something with data</P><P>dataset1.movenext // move to next record</P><P>}

|||

Sorry for the mess. That should read:

dataset1 = SELECT DISTINCT id FROM tableName //populates with 1 entry for each different ID

while(dataset != null){ //loop until out of ID's

dataset2 = SELECT TOP 1 * FROM tableName WHERE id = dataset1.value; // grab top record for each distinct ID

do something with data

dataset1.movenext // move to next record

}

No comments:

Post a Comment