2011-01-06 10 views
3

Ergebnis von SELECT-Anweisung unterscheidet sich von dem Ergebnis von SELECT in VIEW. Wie behebe ich das Problem und bekomme das gleiche Ergebnis von in Sicht?unterschiedliches Ergebnis von SELECT und von SELECT innerhalb einer VIEW

Aktionen Tabelle:

+--+---------+--------------+-----------+------+ 
|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 | 
+--+---------+--------------+-----------+------+ 

wählen:

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; 

Ergebnis:

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

Innenansicht wählen:

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; 
Ergebnis

:

+--+--+------+ 
|p |c |sum | 
+--+--+------+ 
|1 |1 |29.00 | 
|1 |2 |29.00 | 
|2 |1 |29.00 | 
|2 |2 |29.00 | 
+--+--+------+ 
+0

Welche Version von mysql benutzt du? – Jason

+1

Nur zur Information, für Anfänger (auch ich war einer), wenn jemand hilft, eine Lösung anzubieten, und es ist derjenige, der Sie über Ihren Stumpf, es ist eine Höflichkeit, klicken Sie auf das Kontrollkästchen unter ihrer Antwort, um ihnen Kredit, damit andere wissen, die Lösung ist bereits gelöst. – DRapp

+0

ich tat es aber, es ist mir 60 Sekunden warten, bevor ich die Antwort akzeptieren konnte :) – happytoad

Antwort

3

Können Sie nicht tun:

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; 

D.h. befreie die Unterabfragen und baue einfach eine einzige Zusammenfassung (mache action_type_id 2 Werte negativ)

+0

es funktioniert! und es ist so sehr elegant. vielen vielen Dank!! – happytoad

Verwandte Themen