如何组合从数据库派生的两个查询

时间:2018-03-08 08:13:37

标签: mysql union

我有两个问题

$sql1="SELECT MDN, AVG(RSRP),count(case when RSRP !=0 THEN RSRP END) as total from CPE where (month(LAST_UPDATED_TIME)=1) group by MDN";
$sql2="SELECT MDN, AVG(RSRP),count(case when RSRP !=0 THEN RSRP END) as total from CPE where (month(LAST_UPDATED_TIME)=2) group by MDN";

我的问题是如何在一个表中将这两个查询与6列

组合

我尝试了这段代码,但却出错了

select
(SELECT MDN, AVG(RSRP),count(case when RSRP !=0 THEN RSRP END) as total from CPE where (month(LAST_UPDATED_TIME)=1) group by MDN) as 1,
(SELECT MDN, AVG(RSRP),count(case when RSRP !=0 THEN RSRP END) as total from CPE where (month(LAST_UPDATED_TIME)=2) group by MDN) as 2

请帮我解决这个问题..

1 个答案:

答案 0 :(得分:3)

你可以加入

  SELECT t1.MDN
      , AVG(t1.RSRP)
      , count(case when t1.RSRP !=0 THEN t1.RSRP END) as total 
      , t2.avg2 
      , t2.total2
  from CPE t1
  LEFT JOIN(
      SELECT MDN
      , AVG(RSRP) avg2
      ,count(case when RSRP !=0 THEN RSRP END) as total2 
      from CPE 
      where (month(LAST_UPDATED_TIME)=2) 
      group by MDN
  ) t2 on t1.MDN = t2.MDN
  where (month(t1.LAST_UPDATED_TIME)=1) 
  group by t1.MDN