一个查询的多个数学值

时间:2013-10-20 17:53:57

标签: php mysql 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

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

由于

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分: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)。