前提
- DB は PostgreSQL
テーブル構成
- たとえば、以下のようなテーブルがある。
-
test_name
に文字列が入っているはず。たぶん。 -
sts_flg = 1
のデータが有効データ。
test=# \d m_test
列 | 型 | 修飾語
-----------------+-----------------------------+-------------------------------------------------------------
test_no | integer | not null default nextval('m_test_test_no_seq'::class)
test_name | character varying(250) |
sts_flg | smallint | default 1
インデックス:
"m_test_pkey" PRIMARY KEY, btree (test_no)
やいたいこと
- 上記テーブル構成の中から、
test_name
の入っているデータの数がしりたい。 - 空白やNULLは知りたくない。
現在のデータが何件あるか検索してみよ
- 全体は110件ある。ふむふむ
test=# SELECT COUNT(*) FROM m_test WHERE sts_flg = 1;
count
-------
110
(1 行)
NULLと空白以外を抽出する SQL を準備する
-
coalesce
を使用して、NULL/空白ではない文字列を抽出する。 -
coalesce
のtest_name
があるときは、1をかえし、それ以外は 0 を返す。
SELECT COUNT(*)
FROM m_test
WHERE sts_flg = 1
AND (CASE
coalesce(test_name, '') WHEN '' THEN 0
ELSE 1
END
) <> 0;
実行してみる
- やったー!うごいた!100件が空白じゃない。そして残り10件はNULL/空白なのね
test=# SELECT COUNT(*)
test-# FROM m_test
test-# WHERE sts_flg = 1
test-# AND (CASE
test(# coalesce(test_name, '') WHEN '' THEN 0
test(# ELSE 1
test(# END
test(# ) <> 0;
count
-------
100
(1 行)