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.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Efficient way to retrieve groups of records ?

Author  Topic 

pedro
Starting Member

1 Post

Posted - 2005-10-05 : 05:34:51
I have a simple table (uid int, aid int, val varchar)
i.e.
1 1 A
1 2 B
2 1 A
2 2 C
3 1 D
3 2 B

What I want to do is retrieve all the unique uid values for a number of different aid val combinations. For example all the uids that have both (aid=1 and val=A) and (aid=2 and val=B)

I can code this with Having and Group by, but it seems a bit slow as the table is kind of large.
e.g.
SELECT uid FROM table
WHERE (aid=1 and val='A')
OR (aid=2 and val='B')
GROUP BY uid
HAVING count(uid) = 2

Another option I tried is to create a temporary table, insert uids that have aid=1 and val=A, then delete any uids that don't have aid=2 and val=B. This seems to run faster.

Just wondered if anyone had any idea how I can code it up as a more efficient single sql statement.

Or maybe I'm just trying to do something that sql doesn't really want to do.

thanks.

jen
Master Smack Fu Yak Hacker

4110 Posts

Posted - 2005-10-05 : 05:43:41
how did your query work?

aid and val are not even included in the resultset

anyways...

select uid from table
group by uid
having uid in (
SELECT uid FROM table
WHERE (aid=1 and val='A')
OR (aid=2 and val='B'))
and count(*)=2

haven't tested this though...

--------------------
keeping it simple...
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-05 : 06:44:12
>>but it seems a bit slow as the table is kind of large.

Did you use index for key column?

>>For example all the uids that have both (aid=1 and val=A) and (aid=2 and val=B)

But you used Or in your query
Post your expected result

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -