2012-05-10 72 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(正确)