如何将两个查询合并为一个并生成一行

时间:2017-03-24 11:09:59

标签: sql mysqli-multi-query mysqldbcompare

SELECT lp.lead_bucket_no , case when p.product = 'S-400' then qty end as 'S400' , case when p.product = 'Dish Antenna' then qty end as 'DishAntenna' FROM lead_products lp INNER JOIN products p ON p.product_id = lp.product_id WHERE type = 'stock' GROUP BY lead_bucket_no ORDER BY lp.lead_bucket_no

SELECT lp.lead_bucket_no , case when p.product = 'S-400' then qty end as 'S400' , case when p.product = 'Dish Antenna' then qty end as 'DishAntenna' FROM lead_products lp INNER JOIN products p ON p.product_id = lp.product_id WHERE type = 'order' GROUP BY lead_bucket_no ORDER BY lp.lead_bucket_no

如何合并这些查询和获得单行记录。两种查询中只有类型不同。 enter image description here

1 个答案:

答案 0 :(得分:2)

我认为您只想在OR子句中IN(或WHERE):

SELECT lp.lead_bucket_no, 
       SUM(case when p.product = 'S-400' then qty end) as S400,
       SUM(case when p.product = 'Dish Antenna' then qty end) as DishAntenna 
FROM lead_products lp INNER JOIN
     products p
     ON p.product_id = lp.product_id
WHERE type IN ('stock', 'order')
GROUP BY lead_bucket_no
ORDER BY lp.lead_bucket_no;

对于不在GROUP BY子句中的表达式,您还需要某种聚合。您可能还希望按TYPE汇总。目前还不清楚你想要什么样的最终输出。