views:

61

answers:

1

Without using custom functions, is it possible in SQLite to do the following. I have two tables, which are linked via common id numbers. In the second table, there are two variables. What I would like to do is be able to return a list of results, consisting of: the row id, and NULL if all instances of those two variables (and there may be more than two) are NULL, 1 if they are all 0 and 2 if one or more is 1.

What I have right now is as follows:


SELECT 
    a.aid, 
    (SELECT count(*) from W3S19 b WHERE a.aid=b.aid) as num, 
    (SELECT count(*) FROM W3S19 c WHERE a.aid=c.aid AND H110 IS NULL AND H112 IS NULL) as num_null, 
    (SELECT count(*) FROM W3S19 d WHERE a.aid=d.aid AND (H110=1 or H112=1)) AS num_yes 
FROM W3 a

So what this requires is to step through each result as follows (rough Python pseudocode):


if row['num_yes'] > 0:
    out[aid] = 2
elif row['num_null'] == row['num']:
    out[aid] = 'NULL'
else:
    out[aid] = 1

Is there an easier way? Thanks!

+3  A: 

Use CASE...WHEN, e.g.

CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END

Read more from SQLite syntax manual (go to section "The CASE expression").

jmz
Excellent, my thanks for this!
Evan Cortens