2011-01-06 85 views
3

SELECT語句的結果與VIEW中的SELECT結果不同。如何解決問題並從視野中獲得相同的結果?不同的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 | 
+--+--+------+ 
+0

你使用的是哪個版本的mysql? – Jason 2011-01-06 13:17:06

+1

只是FYI,對於新手(我也是一個),當有人幫助提供解決方案時,它是讓你超越你的殘局的一種方法,點擊他們答案下的複選框可以讓他們相信,以便其他人知道解決方案已經解決。 – DRapp 2011-01-06 13:29:43

回答

3

你能不能做:

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; 

即擺脫子查詢,並建立一個單一的總結(使action_type_id 2值爲負)

相關問題