MySQL在一个SELECT中的不同GROUP BY上获得COUNT和SUM

时间:2014-07-31 14:13:47

标签: mysql sql group-by

我需要从表中选择看起来有关此内容的数据:

monthStart  monthEnd newPhones totalPhones oblid
1           1        1         2           1 
2           2        1         2           2
1           2        2         2           3
2           2        1         1           4
2           3        0         3           5

所以我想选择4个字段:month,在monthStart的基础上计算obj的月数,以monthEnd为基础的newPhones的总和,以monthEnd为基础的totalPhones的总和。

因此,对于这些数据,我需要选择:

month  count  totalPhones newPhones
1      3      2           1
2      2      5           4
3      0      3           0

计算第1个月= 3,因为我们有3行,monthStart = 1,但我们只有一行 monthEnd = 1,因此1个月的totalPhones = 2,newPhones = 1 计数为3d month = 0,因为我们有0行,monthStart = 3, 但是我们有3个totalPhones和0个newPhones for monthEnd = 3 - 我们应该显示这个数据。

我坚持这个。我试图从这个选择的结果中选择:

SELECT
monthStart,
monthEnd,
count(1) as uploaded,
sum(newPhones) as newPhones,
sum(totalPhones) as totalPhones
from TestGB
group by monthEnd, monthStart

但我无法得到理想的结果。 谢谢您的帮助!

3 个答案:

答案 0 :(得分:2)

因此,如果有足够的数据显示所有月份,我认为StevieG的回答是有效的。使用较小的数据集(如给定的样本数据),其中月份3在月末,而不是月份启动,则存在问题。然后你需要一些东西来确保所有月份都有代表,我用c做了,合并的只是为了让事情变得漂亮。

SELECT 
  c.month,
  coalesce(a.mycount,0),
  coalesce(b.totalPhones,0),
  coalesce(b.newphones,0)
FROM
  (SELECT monthStart as month FROM TestGB
   UNION
   SELECT monthEnd as month FROM TestGB) c 
LEFT OUTER JOIN 
  (SELECT
   monthStart as month,
   count(distinct obild) as mycount,
   from TestGB
   group by monthStart) a on a.month = c.month
LEFT OUTER JOIN 
  (SELECT
   monthStart as month,
   sum(newPhones) as newPhones,
   sum(totalPhones) as totalPhones
   from TestGB
   group by monthEnd) b ON b.month = c.month

答案 1 :(得分:1)

也许是这样的......

CREATE TABLE #monthstartdata
(
    themonth INT,
    themonthcount int
)

CREATE TABLE #monthenddata
(
    themonth INT,
    totalphones INT,
    newphones INT,
)

INSERT INTO #monthstartdata
            ( themonth, themonthcount )
SELECT monthStart, COUNT(#monthstart) FROM TestGB
GROUP BY monthStart

INSERT INTO #monthenddata
        ( themonth, totalphones, newphones )
SELECT monthEnd, COUNT(totalphones), COUNT(newPhones) FROM TestGB
GROUP BY monthEnd

SELECT #monthstartdata.themonth, themonthcount, totalphones, newphones FROM #monthstartdata
INNER JOIN #monthenddata ON #monthstartdata.themonth = #monthenddata.themonth

答案 2 :(得分:1)

假设我已经正确地理解了这个问题,我怀疑你想用子查询来做这件事。这样的事情:

SELECT 
  IFNULL(a.month,b.month)
  a.mycount,
  b.totalPhones,
  b.newphones
FROM
  (SELECT
   monthStart as month,
   count(distinct obild) as mycount,
   from TestGB
   group by monthStart) a
LEFT OUTER JOIN 
  (SELECT
   monthStart as month,
   sum(newPhones) as newPhones,
   sum(totalPhones) as totalPhones
   from TestGB
   group by monthEnd) b ON a.month = b.month