1

Here is a simple database representation of what I'm stuck on:

IDNumber     TimeSpent         Completed
 1              0                  No
 1              0                  No
 1              2                  No
 2              0                  No
 3              0                  No

I'm currently querying the database as such...

"SELECT Distinct (IDNumber) AS Info FROM TestTable
                                    ORDER BY WorkOrderNumber";

And it gives me back the results

1
2
3

Which is expected.

Now, I'd like to adjust it to where any instance of an IDNumber that have TimeSpent != 0 or Completed != No means that the IDNumber isn't grabbed at all. So for example in the database given, since TimeSpent = 2, I don't want IDNumber 1 to be returned in my query at all.

My first instinct was to jump to something like this...

"SELECT Distinct (IDNumber) AS Info FROM TestTable
                                    WHERE TimeSpent='0' AND Completed='No'
                                    ORDER BY WorkOrderNumber";

But obviously that wouldn't work. It would correctly ignore one of the IDNumber 1's but since two others still satisfy the WHERE clause it would still return 1.

Any pointers here?

4

2 に答える 2

2
SELECT DISTINCT IDNumber
FROM TestTable
WHERE IDNumber NOT IN 
    (SELECT IDNUmber FROM TestTable WHERE TimeSPent <> 0 OR Completed <> 'No')
于 2013-03-24T23:21:10.753 に答える
1

You can do this with an aggregation, using a having clause:

select IDNumber
from TestTable
group by IDNumber
having sum(case when TimeSpent = 0 then 1 else 0 end) = 0 and 
       sum(case when Completed = 'No' then 1 else 0 end) = 0

The having clause is counting the number of rows that meet each condition. The = 0 is simply saying that there are no matches.

I prefer the aggregation method because it is more flexible in terms of the conditions that you can set on the groups.

于 2013-03-24T23:27:05.347 に答える