可以执行“SUM”子查询或应该做什么?

时间:2016-07-14 18:25:15

标签: mysql sql

我试图通过此查询得到一些结果,问题是当我尝试使用“GROUP BY c.campus”而没有YEAR(a.period_end)时,显然得到校园分组的结果,再加上排序就像“2012年,2013年,2014年,2015年”一样,问题是EndYear混合,而不是显示所有年份......提前感谢。

现在查询:

SELECT DISTINCT a.user, a.service, GROUP_CONCAT(b.account) accounts,
YEAR(a.period_end) AS EndYear,
SUM(a.consum) AS SumConsumEngy,
SUM(a.cost) AS SumCostEngy, c.campus
FROM `sdspanel1`.`pdc_consum_engy` a
INNER JOIN `sdspanel1`.`ctrl_services` b ON(a.servicio = b.id)
INNER JOIN `sdspanel1`.`pdc_services_engy` c ON(c.accuont = b.account)
WHERE c.campus IS NOT NULL AND c.campus <> '' 
AND a.period_end IS NOT NULL AND a.period_end <> ''
GROUP BY YEAR(a.period_end), c.campus, b.account, a.service, a.user
ORDER BY YEAR(a.period_end) ASC ;

现在选择结果:

 user    service accounts  EndYear SumConsumEngy SumCostEngy   Campus
  4         14   191,191   2012     9919293      33339493     cname1
  4         23   238,388   2012     9283182      31931993     cname1
  4         14   191,191   2013     999293       3939493      cname1
  4         14   191,191   2013     991293       939493       cname1
  4         23   238,388   2014     9183182      31432993     cname2
  4         23   238,388   2012     9083182      31731993     cname2
  4         14   191,191   2012     9999293      36539403     cname2
  4         23   238,388   2013     9283182      32931923     cname2
  4         14   191,191   2013     9919293      33039843     cname2
  4         23   238,388   2014     9283182      31231993     cname2

让我解释得更好或更好,主要是按校园分组,“SUM”“再次”或任何其他查询或意味着SumConsEngy和SumCostEngy,EndYear应该是“按年度排序(a.period_end)ASC”, SConsum ####和SCost ####应该是相应校园的新年数。当我尝试查询时,仅按“c.campus”分组,它不显示所有年份。

我要求的是这样的:

 user service  accounts  EndYear SumConsumEngy SumCostEngy   Campus
  4   snumbers acnumbers   2012   SConsum2012  SCost2012     cname1
  4   snumbers acnumbers   2013   SConsum2013  SCost2013     cname1
  4   snumbers acnumbers   2014   SConsum2014  SCost2014     cname1
  4   snumbers acnumbers   2015   SConsum2015  SCost2015     cname1
  4   snumbers acnumbers   2016   SConsum2016  SCost2016     cname1
  4   snumbers acnumbers   2011   SConsum2011  SCost2011     cname2
  4   snumbers acnumbers   2012   SConsum2012  SCost2012     cname2
  4   snumbers acnumbers   2013   SConsum2013  SCost2013     cname2
  4   snumbers acnumbers   2014   SConsum2012  SCost2012     cname2
  4   snumbers acnumbers   2015   SConsum2012  SCost2012     cname2
  4   snumbers acnumbers   2016   SConsum2012  SCost2012     cname2

依旧......

1 个答案:

答案 0 :(得分:0)

是否要从b.account, a.service, a.user中移除GROUP BY,并可能使用GROUP_CONCAT(DISTINCT b.account)