GROUP BY和交错值

时间:2016-06-04 16:14:48

标签: mysql group-by

我有一张存储消耗能量测量值的表格。如果我想知道能量成本,我可以选择给定时间段的行,然后选择第一行和最后一行,计算差值并乘以价格。问题是如果有两种关税,它们会不时切换:

kWh  | tariff | time_stamp |
123  | G11    |    t+0     |
130  | G11    |    t+1     |
132  | G11    |    t+2     |
140  | G12    |    t+3     |
143  | G12    |    t+4     |
150  | G11    |    t+5     |
161  | G11    |    t+6     |

我需要以某种方式按关税分组,但每次关税变化时我都需要新组。所以在上面的例子中会有三组,而不是两组。只有两种关税,G11和G12。我可以使用GROUP BY或其他东西吗?

1 个答案:

答案 0 :(得分:2)

您可以使用用户定义的变量,该变量在每次关税变化时递增。

SELECT tariff, MIN(time_stamp) AS mintime, MAX(time_stamp) AS maxtime
FROM (
    SELECT t1.*, @counter := IF(tariff = @last_tariff, @counter, @counter+1) AS counter, @last_tariff := tariff
    FROM (SELECT *
          FROM yourTable
          ORDER BY time_stamp) AS t1
    JOIN (SELECT @last_tariff := null, @counter := 0) AS vars) AS grouped
GROUP BY tariff, counter

要获取表格的相应行,您可以将其与原始表格结合使用,如SQL Select only rows with Max Value on a Column

中所述