1

I am developing a SQL query that currently works for one group/mode combination. But I want this query to work for all groups and modes. And include each combination one time only. But in source data there are many other columns, so there is more than one record per combination.

So my source table structure is:

group   mode   p-val
-----   ----   ------
A       B      4.567
C       D      3.694

How can I setup a loop to loop through each group/mode combination? And I'd rather not use cursors!

3
  • Please format your posts correctly as previously requested. What is the loop doing on each step? If it is something inherently procedural then there would be no particular reason to use another looping construct rather than cursors (as they are specifically designed for looping through rows of results). Best would be to rewrite it in a set based way though but you have given us precisely zero information to go off here. Commented May 12, 2011 at 22:31
  • Is what you are showing sample inputs or expected outputs? Commented May 12, 2011 at 22:33
  • @Thomas, this is sample input. Commented May 13, 2011 at 15:41

2 Answers 2

2

A very broad and general question. Here's a broad and general answer.

First, write a query to extract the set of the values you are interested in, such that each set is unique. SELECT DISTINCT... and SELECT... GROUP BY... suggest themselves.

This data could be stored as a temp table, included as a subquery, or just made part of the overall final query. The best to use depends entirely on what you're working on.

Next, write your "main" processing query using this subset as a basis. Something like ...FROM <theSubset> INNER JOIN <etc>.

Done properly (I'm not saying it'd be easy), the effects of this set-based methodology are quite similar to the results achieved with procedural looping.

Sign up to request clarification or add additional context in comments.

1 Comment

I apologize for the generalness of my question. But the problem is difficult to explain fully. However, I have fixed this problem using set-based vs. cursor approach now! It took alot of work, but I was able to loop through a WHILE loop to implement this logic
2

This is called JOIN in sql. i.e. the statement

SELECT * FROM table AS a JOIN table AS b;

results

a | b | 4.5   | a | b | 4.5
a | b | 4.5   | c | d | 3.694
c | d | 3.694 | a | b | 4.5
c | d | 3.694 | c | d | 3.694

now you have all combinations of [group,mode] records. Read more on JOINs from Google.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.