前提・実現したいこと
下記のテーブルを基にそれぞれのSELECT文を作成しました。
これを①+②ー③のようにまとめ、amountがマイナスのものを削除したレコードを取り出したいのですが、うまくできません。
MySQL
1 2①select MAX(id) AS `id` from t_transactions group by tran_grp; 3 4②select id from t_transactions where settle_grp IS not null; 5 6③select settle_grp from t_transactions where settle_grp IS NOT NULL group by settle_grp;
table
1id payment_date amount tran_grp settle_grp 2132 2019/7/1 20 132 NULL 3133 2019/7/1 -20 132 NULL 4134 2019/7/1 20 132 NULL 5135 2019/10/1 1000 135 NULL 6137 2019/10/1 1000 137 NULL 7138 2019/10/1 -1000 137 NULL 8139 2019/10/1 1000 137 NULL 9140 2019/10/1 -1000 137 139 10141 2019/11/1 300 137 139 11142 2019/11/3 700 137 139 12143 2019/11/3 -700 137 142 13144 2019/11/3 300 137 142 14145 2019/11/10 400 137 142 15
該当のソースコード
#①+②ー③の結果 id payment_date amount tran_grp settle_grp 134 2019/7/1 20 132 NULL 135 2019/10/1 1000 135 NULL 140 2019/10/1 -1000 137 139 141 2019/11/1 300 137 139 143 2019/11/3 -700 137 142 144 2019/11/3 300 137 142 145 2019/11/10 400 137 142
#最終的にほしいレコード id payment_date amount tran_grp settle_grp 134 2019/7/1 20 132 NULL 135 2019/10/1 1000 135 NULL 141 2019/11/1 300 137 139 144 2019/11/3 300 137 142 145 2019/11/10 400 137 142
試したこと
SQLを分割して、InnerJoinでつなげようと思いましたが下記エラーがでてしまいました。
どうぞよろしくお願いいたします。
MySQL
1#①+② 2 3 SELECT MAX(id) AS `id` from t_transactions group by tran_grp AS join1 4INNER JOIN select `id` from t_transactions where settle_grp IS not null AS join2 5 ON join2.id = join1.id;
発生している問題・エラーメッセージ
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS join1 INNER JOIN select `id` from t_transactions where settle_grp IS not null' at line 1
補足情報(FW/ツールのバージョンなど)
mysql 5.7
追記 ①+②ー③までをサブクエリを利用して作成できました。ここからマイナス分を削除しようと思います。
SELECT * FROM t_transactions WHERE t_transactions.id = ( SELECT MAX(id) FROM t_transactions AS tmp WHERE t_transactions.tran_grp = tmp.tran_grp ) or settle_grp IS not null and id NOT IN ( select settle_grp from t_transactions where settle_grp IS NOT NULL group by settle_grp );
回答3件
あなたの回答
tips
プレビュー