从子查询中选择多个字段

时间:2014-10-12 17:20:38

标签: mysql sql

我有下一个查询:

SELECT
    a.Date,
    (SELECT SUM(Used), SUM(Max) FROM Switch_Statistic b WHERE Date = (SELECT MAX(Date) FROM Switch_Statistic WHERE Switch_ID = b.Switch_ID AND Date <= a.Date))
FROM Switch_Statistic a
GROUP BY Date;

如您所见,我需要从子查询中选择SUM(Used), SUM(Max)。使用CONCAT并不是一个好方法!


表架构:

ID --- Switch_ID --- Date --- Max --- Used

一些数据:

1   641 2014-10-04  2   16
20  630 2014-10-04  1   7
24  634 2014-10-04  0   8
26  641 2014-10-06  2   16
32  641 2014-10-07  2   16
35  641 2014-10-08  3   16
39  641 2014-10-09  2   16
64  293 2014-10-10  1   22
...
557 38  2014-10-12  3   22
559 293 2014-10-12  1   22
563 294 2014-10-12  6   22
565 641 2014-10-12  2   16

我需要什么: CONCAT_WS的示例

mysql> SELECT
    a.Date,
    (SELECT CONCAT_WS('/', SUM(Used), SUM(Max)) FROM Switch_Statistic b WHERE Date = (SELECT MAX(Date) FROM Switch_Statistic WHERE Switch_ID = b.Switch_ID AND Date <= a.Date)) AS Result
FROM Switch_Statistic a
GROUP BY Date;
+------------+----------+
| Date       | Result   |
+------------+----------+
| 2014-10-04 | 3/31     |
| 2014-10-06 | 3/31     |
| 2014-10-07 | 3/31     |
| 2014-10-08 | 4/31     |
| 2014-10-09 | 3/31     |
| 2014-10-10 | 249/1587 |
| 2014-10-11 | 354/2147 |
| 2014-10-12 | 360/2185 |
+------------+----------+
8 rows in set (0.26 sec)

查询逻辑: 1)从表中选择所有日期 2)SUM - 当前日期使用和最大,如果Switch_ID没有此日期的记录,则选择表中存在的最后一个

链接到sqlfiddle - http://sqlfiddle.com/#!2/c3d479

1 个答案:

答案 0 :(得分:1)

您应该只使用聚合而不使用子查询或连接来执行此操作:

  SELECT date, sum(used) as used, sum(max) as max
  FROM switch_statistic ss
  where ss.date = (select max(date) from Switch_Statistics ss2 where ss2.Switch_id = ss.SwitchId
  GROUP BY ss.date;

编辑:

您似乎想要累积总和。在MySQL中,通常最好使用变量来完成:

SELECT date, used, max, (@u := @u + used) as cumeused, @m := @m + max) as cumemax
fROM (SELECT date, sum(used) as used, sum(max) as max
      FROM switch_statistic ss
      GROUP BY ss.date
     ) ss CROSS JOIN
     (SELECT @u := 0, @m := 0) vars
ORDER BY date;