いつもありがとうございます。nullの取扱いに手こずっております。
いま、在庫受払台帳の集計のようなものをイメージし、DBには繰越残,入庫,出庫があり(違和感ありますがとりあえず繰越残は所与)、selectしたときに在庫(繰越+入庫ー出庫)を計算して表示するということするものとします。
問題はnullが混在すると結果はnullになってしまうことです。そこで、回避すべく、nullの場合は計算式に入れないようにcase式で対応しました。
本来はnullだったら数値としての0、というふうにしたいのですが見た目は0になっても文字列としての0という解釈しかしれくれないのか、うまくいかなかったために在庫を計算するタイミングでcase式を入れました。
ほかにもっとスマートな書き方があればご教示のほど、よろしくお願い致します。
lang
1sqlite> .schema test 2CREATE TABLE test (s1 integer, s2 integer, s3 integer); 3 4// サンプルデータ投入後 5sqlite> select * from test; 6s1 s2 s3 7-------- ---------- -------- 810 10 5 9 10 5 10 10 1110 1210 5 1310 10 14 15 16sqlite> select s1, s2, s3, 17 ...> case when s1 is null and s2 is not null and s3 is not null then s2-s3 18 ...> when s1 is null and s2 is not null and s3 is null then s2 19 ...> when s1 is not null and s2 is null and s3 is null then s1 20 ...> when s1 is not null and s2 is null and s3 is not null then s1-s3 21 ...> when s1 is not null and s2 is not null and s3 is null then s1+s2 22 ...> else s1+s2-s3 end 23 ...> from test; 24 25// 結果 2610|10| 5|15 27 |10| 5| 5 28 |10| |10 2910| | |10 3010| | 5| 5 3110|10| |20 32
sqlite3 --version 3.6.20

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/06/18 07:02
2015/06/18 07:03
2015/06/18 07:06
2015/06/18 07:06
2015/06/18 07:08
2015/06/18 07:20
2015/06/18 08:09
2015/06/18 08:14