mysqlのgroup_by&havingについて

便利なグルーピングについて

前提条件

create table db_name.household_account_book
                     (date date,
                      expense_item varchar(20),
                      memo varchar(100),
                      deposit_amount integer,
                      amount_invested integer)

前回と同じ条件です。

sqlの検索結果の加工 - mikami's engineer diary

使い方

mysql> select expense_item, sum(amount_invested) as total_amount_invested
    ->   from household_account_book
    ->  group by expense_item;
+-----------------+-----------------------+
| expense_item    | total_amount_invested |
+-----------------+-----------------------+
| 交際費          |                  5000 |
| 教育娯楽費      |                  2800 |
| 水道光熱費      |                  7560 |
| 給料            |                     0 |
| 食費            |                   260 |
+-----------------+-----------------------+

こうなります。

ここから、sum(amount_invested) > 0という、結果がほしいとします。

このgroup_byで集計したものに対して、whereで絞り込みはできないので、代わりにhavingを使います。

select expense_item, sum(amount_invested) as total_amount_invested
  from household_account_book
group by expense_item
having sum(amount_invested) > 0;
+-----------------+-----------------------+
| expense_item    | total_amount_invested |
+-----------------+-----------------------+
| 交際費          |                  5000 |
| 教育娯楽費      |                  2800 |
| 水道光熱費      |                  7560 |
| 食費            |                   260 |
+-----------------+-----------------------+

これで消えます。

wherehavingは検索条件の絞り込みなのに、集計したかどうかで、使い方が異なります。

以上です。