将值从行移动到另一行?

时间:2013-07-05 05:55:35

标签: mysql sql

enter image description here

我有一张像figure (1)这样的表格。 10000是12个月所有产品的moneyStock。 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。

更新:表格结构已添加。

enter image description here

3 个答案:

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

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

正在使用 DEMO!

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