質問

SELECTステートメントからの結果VIEW内のSELECTからの結果と異なっています。どのように問題を修正し、ビュー内から同じ結果を取得する?

アクションテーブルます:

+--+---------+--------------+-----------+------+
|id|person_id|action_type_id|currency_id|sum   |
+--+---------+--------------+-----------+------+
|1 |1        |1             |1          | 1.00 |
|2 |1        |1             |1          | 5.00 |
|3 |1        |1             |2          |10.00 | 
|4 |1        |2             |1          | 2.00 |
|5 |2        |1             |1          |20.00 |
|6 |2        |2             |2          | 5.00 |
+--+---------+--------------+-----------+------+

を選択します:

SELECT person_id AS p, currency_id AS c,
(
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=1 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2)) -
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=2 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2))
) AS sum
FROM actions
GROUP BY currency_id, person_id
ORDER BY person_id, currency_id;

結果:

+--+--+------+
|p |c |sum   |
+--+--+------+
|1 |1 | 4.00 |
|1 |2 |10.00 |
|2 |1 |20.00 |
|2 |2 |-5.00 |
+--+--+------+

内のビューを選択します:

CREATE VIEW p_sums AS
SELECT person_id AS p, currency_id AS c,
(
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=1 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2)) -
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=2 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2))
) AS sum
FROM actions
GROUP BY currency_id, person_id
ORDER BY person_id, currency_id;

SELECT * FROM p_sums;

結果:

+--+--+------+
|p |c |sum   |
+--+--+------+
|1 |1 |29.00 |
|1 |2 |29.00 |
|2 |1 |29.00 |
|2 |2 |29.00 |
+--+--+------+
役に立ちましたか?

解決

あなたが行うことはできません。

SELECT person_id AS p, currency_id AS c, SUM(CASE action_Type_id WHEN 1 THEN sum WHEN 2 THEN -sum END) as sum
FROM actions
GROUP BY currency_id, person_id
ORDER BY person_id, currency_id;

すなわち。サブクエリを取り除くと、1つだけの合計を構築する(作りは2つの値をaction_type_id負)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top