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 有两个记录。我想要两列,每列一列。我在问是否可以通过一个查询来完成?

谢谢

4

3 回答 3

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);
于 2013-10-20T19:13:44.703 回答
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

于 2013-10-20T18:49:11.680 回答
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上查看(再次感谢 @kordirko)。

于 2013-10-21T22:08:43.867 回答