如何根据if条件将行拆分为2

时间:2017-10-24 12:57:27

标签: mysql

我对以下过程感到震惊。我有两个名为table1& amp;表2。 table1包含当前状态的总金额。 table2包含填充金额。 我希望得到结果,如果table1.status = 'cancel'那么我需要得到2行,如预期结果所示。有没有办法做到这一点?

表1

unq_id | amount | status  | type
   1      4       'cancel'  'two'
   2      2       'done'    'one'

表2

p_id | unq_id | filled
  1      1      1   
  2      2      2  


我的查询

SELECT 
  a.unq_id as id_val,
  (IFNULL(b.filled,0)) as filled 
FROM 
  table1 AS a 
  LEFT JOIN table2 AS b 
    ON a.unq_id = b.unq_id 
WHERE 
  (a.status = "done" 
  OR a.status = "cancel")

当前结果

id_val | filled
  1      1
  2      2

预期结果

id_val filled
  1      3 (cancelled amount [ 4 - filled amount])
  1      1 (filled amount)
  2      2

2 个答案:

答案 0 :(得分:0)

您可以使用下面的查询

SELECT 
  a.unq_id as id_val,
  ABS(opt-IFNULL(b.filled,0)) as filled
FROM 
  (select *, 0 as opt from table1 
   union all
   select *,4 as opt from table1 where status = "cancel")AS a 
  LEFT JOIN table2 AS b 
    ON a.unq_id = b.unq_id 
WHERE 
  (a.status = "done" 
  OR a.status = "cancel")

答案 1 :(得分:0)

你可以使用Union ... 您已经拥有的查询的第一部分,为您提供部分结果。您只需要向其添加第二个查询以获取结果的其余部分:

SELECT a.unq_id as id_val,(ISNULL(b.filled,0)) as filled FROM 
Tab1 AS a LEFT JOIN Tab2 AS b ON a.unq_id = b.unq_id 
WHERE (a.status = "done" OR a.status = "cancel")

UNION

SELECT a.unq_id as id_val, a.amount - b.filled as filled FROM 
Tab1 AS a LEFT JOIN Tab2 AS b ON a.unq_id = b.unq_id 
WHERE (a.status = 'cancel')

ORDER BY id_val