2013-10-20 53 views
0

我遇到了一個查詢的問題。來自一個查詢的多個數學值

SELECT 
     CASE WHEN b.value IS NULL 
     THEN sum(d.value) 
     ELSE sum(d.value) + sum(b.value) 
     END AS sumaWydatkow 

     FROM data d 
     LEFT JOIN data_bills b 
     ON d.id = b.data_id 
     WHERE d.type = 0 

     UNION 

     SELECT 

     CASE WHEN b.value IS NULL 
     THEN sum(d.value) 
     ELSE sum(d.value) + sum(b.value) 
     END AS sumaPrzychodow 

     FROM data d 
     LEFT JOIN data_bills b 
     ON d.id = b.data_id 
     WHERE d.type = 1 

我要總結兩個欄,或者如果他們中的一個(data_bills)是空的,總和只有一張桌子,有兩個版本列類型,0和1

但現在是一個clumn有兩個記錄。我需要兩列,每列一列。 我在問是否可以用一個查詢完成?

感謝

+1

我不完全按照。也許一些樣本數據和期望的結果將有助於說明您的問題? – eggyal

+0

想要總結兩列。這些列在兩個不同的表上。但我想用一個QUERY來做到這一點。有了UNION,我有一個coolumn結果,包含兩條QUERY記錄。但是我想要在兩列中輸出結果,每列有一條記錄:)感謝您的重播 – Grzegorz

+2

也許某些**樣本數據**和**所需的結果**有助於說明您的問題? – eggyal

回答

0

嘗試此查詢:

SELECT 
     (SELECT 
     CASE WHEN b.value IS NULL 
     THEN sum(d.value) 
     ELSE sum(d.value) + sum(b.value) 
     END AS sumaWydatkow 

     FROM data d 
     LEFT JOIN data_bills b 
     ON d.id = b.data_id 
     WHERE d.type = 0 
     ) type0, 

     (SELECT 
     CASE WHEN b.value IS NULL 
     THEN sum(d.value) 
     ELSE sum(d.value) + sum(b.value) 
     END AS sumaPrzychodow 

     FROM data d 
     LEFT JOIN data_bills b 
     ON d.id = b.data_id 
     WHERE d.type = 1 
    ) type1 

演示 - >http://www.sqlfiddle.com/#!2/6ec52/2

0

你爲什麼這樣做:

CASE WHEN b.value IS NULL 
    THEN sum(d.value) 
    ELSE sum(d.value) + sum(b.value) 
    END 

?這將基於是否在某些任意行的b.value中包含sum(b.value)。你大概的意思只是:sum(d.value) + coalesce(sum(b.value),0) (話說CASE WHEN sum(b.value) IS NULL...將相當於)

我會做這樣(感謝小提琴,kordirko):

SELECT 
    sum(if(d.type=0, coalesce(d.value,0)+coalesce(b.value,0), null)) type0, 
    sum(if(d.type=1, coalesce(d.value,0)+coalesce(b.value,0), null)) type1 
FROM data d 
LEFT JOIN data_bills b 
ON d.id = b.data_id 
WHERE d.type in (0,1); 
0
SELECT d.type, SUM(d.value) + SUM(b.value) 
FROM  data d LEFT JOIN data_bills b ON b.data_id = d.id 
WHERE d.type IN (0,1) 
GROUP BY d.type 

看到它在sqlfiddle(再次,與thanks to @kordirko)。