all groups > sql server programming > june 2004 >
You're in the

sql server programming

group:

need help to create query



need help to create query Daniel
6/20/2004 6:05:27 PM
sql server programming: hi,
I had a table like below:

id status
----------------------------
82 N
82 N
83 N
83 Y
83 N
81 N
----------------------------

My question is: how to filter out 82,81 because i only want to choose id
whose all status is N!

It really confused me, and i have no way out!
I really appreciate you help, thanks ahead!

Re: need help to create query Steve Kass
6/20/2004 9:55:03 PM

[quoted text, click to view]

You could still please your schoolteacher with

select distinct a.id
from YourTable as a
where 'N' = ALL (
select b.status
from YourTable as b
where b.id = a.id
)

I'm not sure, however, that SQL Server optimizes ALL queries as well as
EXISTS queries.

Steve Kass
Drew University

[quoted text, click to view]

Re: need help to create query Hugo Kornelis
6/21/2004 12:14:16 AM
[quoted text, click to view]

Hi Daniel,

You didn't post any DDL, so I'll just have to make a guess:

SELECT DISTINCT id
FROM YourTable AS a
WHERE NOT EXISTS
(SELECT *
FROM YourTable AS b
WHERE b.id = a.id
AND b.status <> 'N')
(untested)

Translation in plain English: list all id's for which there is no status
that is not 'N'.

At school I was taught "Don't use no double negations, not never!" This is
something I had to unlearn when I started doing SQL <g>

Best, Hugo
--

Re: need help to create query John Gilson
6/21/2004 1:40:56 AM
[quoted text, click to view]

Assume table T and status values being Y or N.

SELECT id
FROM T
GROUP BY id
HAVING MAX(status) = 'N'

--
JAG

Re: need help to create query Hugo Kornelis
6/21/2004 8:48:00 PM
[quoted text, click to view]

Hi Steve,

Neat! I always forget about the ANY and ALL operators. That's because I
never use them - and I never use them because I forget about them. Thanks
for the reminder.

Seriously though - double negations are really the key to many common
query problems. If I find myself stuck in a query, my first course of
action is to negate the question - "Okay, so which rows do I NOT want to
see in this result set??"

Best, Hugo
--

AddThis Social Bookmark Button