0

在此处输入图像描述

我有一张像figure (1). 10000 是所有产品 12 个月的货币库存。5000 是 12 个月产品 384 的 moneyStock。现在我喜欢得到钱,moneyStock 和产品 384 的总和figure (3)。怎么做?图(2)是我试过的:

SELECT siire_code, zaiko_code, month_str, money
FROM test
WHERE siire_code = 384 OR (siire_code = 560 AND zaiko_code = 384)
GROUP BY month_str, zaiko_code

注意:560是所有产品所有月份的 moneyStock 的 id。

更新:添加了表格结构。

在此处输入图像描述

4

3 回答 3

2
select a.month_str,a.money,ifnull(b.moneyStock,0) moneyStock, 
       a.money+ifnull(b.moneyStock,0) total
from (select siire_code code,month_str, sum(money) money
        from yourtable
        where siire_code = 384
        group by siire_code,month_str)a 
left outer join 
        (select zaiko_code code, month_str, sum(money) moneyStock
        from yourtable
        where siire_code =560 
        and zaiko_code =384
        group by zaiko_code, month_str) b
on (a.code = b.code
and a.month_str = b.month_str)

在此处查看SQLFiddle 演示

于 2013-07-05T06:17:16.920 回答
2
SELECT
  s.month_str,
  s.money,
  IFNULL(z.money, 0) 'moneyStock',
  (IFNULL(z.money, 0) + s.money) 'total'
FROM
  Source s
LEFT JOIN
    Source z
  ON
      s.siire_code = z.zaiko_code
    AND
      s.month_str = z.month_str
    AND
      z.siire_code = 560
WHERE
  s.siire_code = 384

工作演示!

于 2013-07-05T06:17:49.810 回答
1

这个怎么样:

SELECT month_str, sum(one_t.money), sum(other_t.money), sum(all_t.money)
FROM   test
       LEFT JOIN test one_t
         ON test.siire_code = one_t.siire_code
       LEFT JOIN test other_t
         ON test.siire_code = other_t.zaiko_code
       LEFT JOIN test all_t
         ON test.siire_code = all_t.siire_code
            OR test.siire_coe = one_t.zaiko_code
WHERE  siire_code = 384
       OR (siire_code = 560
           AND zaiko_code = 384)
GROUP  BY month_str
于 2013-07-05T06:15:18.927 回答