2012-05-10 73 views
0

我有一個simmelar porblem, 我想在下面的查詢中總結「totaal_inclusief_btw」: 有人可以幫我解決這個問題嗎?無法弄清楚。MySQL - SUM和AS一樣SUM(test1)AS test2,SUM(test2)

表1(facturen)

factuur_id factuur_datum factuur_btw_weergave 
--------------------------------------------------------------------------- 
1    2012-05-10  inclusief 
2    2012-05-10  exclusief 

TABEL 2(factuur_regels)

regel_id regel_factuur_id regel_aantal regel_bedrag regel_btw 
--------------------------------------------------------------------------- 
18   1     1    40    19 
19   1     2    40    6 
20   2     1    40    19 
21   2     2    40    6 

使用以下查詢:

SELECT 
CASE  
WHEN factuur_btw_weergave = 'inclusief' 
THEN SUM(regel_bedrag*regel_aantal) 
WHEN factuur_btw_weergave = 'exclusief' 
THEN SUM(((regel_bedrag*regel_aantal)/100)*(100+regel_btw)) 
END 
AS totaal_inclusief_btw, 
SUM(totaal_inclusief_btw) AS new 
FROM factuur_regels 
INNER JOIN facturen ON factuur_id = regel_factuur_id 
GROUP BY factuur_datum 

我得到錯誤:

#1054 - Unknown column 'totaal_inclusief_btw' in 'field list' 

當我離開的第二SUM 「SUM(totaal_inclusief_btw)隨着新」:

SELECT 
CASE WHEN factuur_btw_weergave = 'inclusief' THEN SUM(regel_bedrag*regel_aantal) 
     WHEN factuur_btw_weergave = 'exclusief' THEN SUM(((regel_bedrag*regel_aantal)/100)*(100+regel_btw)) 
     END 
     AS totaal_inclusief_btw 

FROM factuur_regels 
LEFT JOIN facturen ON factuur_id = regel_factuur_id 
WHERE factuur_datum = '2012-05-10' 
GROUP BY factuur_datum 

我會得到這樣的結果:

totaal_inclusief_btw: 
240 (this needs to be 252,4) 

當我集團通過「factuur_id 「:

SELECT 
CASE WHEN factuur_btw_weergave = 'inclusief' THEN SUM(regel_bedrag*regel_aantal) 
     WHEN factuur_btw_weergave = 'exclusief' THEN SUM(((regel_bedrag*regel_aantal)/100)*(100+regel_btw)) 
     END 
     AS totaal_inclusief_btw 

FROM factuur_regels 
LEFT JOIN facturen ON factuur_id = regel_factuur_id 
WHERE factuur_datum = '2012-05-10' 
GROUP BY factuur_id 

,我會得到這樣的結果:

totaal_inclusief_btw: 
120 
132.4 

我希望有人能幫助我解決這個查詢! THANK YOU

+0

您是否嘗試過使用和**圍繞** CASE聲明(而不是內部)和由factuur_id分組? –

回答

1

問題解決

現在適用於以下查詢:

SELECT factuur_datum, SUM(totaal_inclusief_btw) 
FROM (
       SELECT factuur_datum, 
       CASE WHEN factuur_btw_weergave = 'inclusief' THEN SUM(regel_bedrag*regel_aantal) 
          WHEN factuur_btw_weergave = 'exclusief' THEN SUM(((regel_bedrag*regel_aantal)/100)*(100+regel_btw)) 
          END 
          AS totaal_inclusief_btw 
       FROM factuur_regels 
       LEFT JOIN facturen ON factuur_id = regel_factuur_id 
       WHERE factuur_datum = '2012-05-10' 
       GROUP BY factuur_id 
       )q 

該查詢將返回:252.4(正確)