Firebird:select语句中两个字段相乘的总和

时间:2013-12-03 14:37:34

标签: sql case firebird multiplication

基本上我需要的是得到两个场的乘法之和。

例如:SUM ((field_1 or field_2) * field_3)

field_1field_2是根据第四个字段field_4

的值选择的

我的表:

field_1: Float
field_2: Float
field_3: Float
field_4: Char

简而言之,我需要的是这样的事情:

SELECT
...
IF field_4 = 'K'
THEN
    SUM( field_1 * field_3 )
ELSE
    SUM( field_2 * field_3 )

我尝试过使用IF和CASE语句,但我无法使其正常工作。 这是我真正的疑问:

SELECT  
    D.id,
    D.name,
    SUM(CASE WHEN D.sale_unity = 'K' 
        THEN (D.cost_price * CI.quantity_k)
        ELSE (D.cost_price * CI.quantity_u) ) AS total_cost,
    SUM(CASE WHEN D.sale_unity = 'K' 
        THEN (D.sale_price * CI.quantity_k)
        ELSE (D.sale_price * CI.quantity_u) ) AS net
FROM DETAIL D
INNER JOIN VOUCHER AS V ON V.id = D.voucher_id
WHERE V.client_id = 97 AND V.date BETWEEN '06/01/2012' AND '07/01/2012'
GROUP BY D.id, D.name 

1 个答案:

答案 0 :(得分:4)

我认为您的查询错误在于您的CASE语句缺少END。试试这个:

SELECT  
    D.id,
    D.name,
    SUM(CASE WHEN D.sale_unity = 'K' 
        THEN (D.cost_price * CI.quantity_k)
        ELSE (D.cost_price * CI.quantity_u) END ) AS total_cost,
    SUM(CASE WHEN D.sale_unity = 'K' 
        THEN (D.sale_price * CI.quantity_k)
        ELSE (D.sale_price * CI.quantity_u) END ) AS net
FROM DETAIL D
INNER JOIN VOUCHER AS V ON V.id = D.voucher_id
WHERE V.client_id = 97 AND V.date BETWEEN '06/01/2012' AND '07/01/2012'
GROUP BY D.id, D.name