MySQL有条件的分组

时间:2018-05-09 19:46:04

标签: mysql sql

我有这样的数据:

+---------------+------+
| timestamp     | robo |
+---------------+------+
| 1518259341785 | A    |
| 1518259341785 | A    |
| 1518259341785 | A    |
| 1518259341785 | RE   |
+---------------+------+

和此:

+---------------+------+
| timestamp     | robo |
+---------------+------+
| 1518259341788 | RE   |
| 1518259341788 | RE   |
| 1518259341788 | RE   |
| 1518259341788 | A    |
+---------------+------+

众所周知,如果我们使用这个SQL对数据进行分组并计算行数:

SELECT timestamp, robo, COUNT(*) AS num_rows
FROM tables
GROUP BY timestamp

num_rows将是4.如何在时间戳中将条件only if robo RE = 1的数据分组。这样1518259341788组就不会计算/出现了。谢谢。

更新: 无条件分组的结果:

+---------------+------+----------+
| timestamp     | robo | COUNT(*) |
+---------------+------+----------+
| 1518259341785 | A    |        4 |
| 1518259341788 | A    |        4 |
+---------------+------+----------+

与条件分组的预期结果:

+---------------+------+----------+
| timestamp     | robo | COUNT(*) |
+---------------+------+----------+
| 1518259341785 | A    |        4 |
+---------------+------+----------+

3 个答案:

答案 0 :(得分:2)

如果您想获得每个timestamp值的记录数,但只有当RE值的timestamp记录数为1时,您才可以这样做这样:

SELECT timestamp, COUNT(*) AS num_rows
  FROM tables
 GROUP BY timestamp
HAVING SUM(CASE WHEN robo = 'RE' THEN 1 ELSE 0 END) = 1

答案 1 :(得分:1)

您可以在子选择中使用内部联接来获取时间戳,只有一个count = 1,因为robo = RE

  SELECT timestamp, robo, COUNT(*) AS num_rows
  FROM tables
  INNER join (
    select timestamp
    from tables
    where robo ='RE'
    group by timestamp 
    having count(*) = 1
    ) t on tables.timestamp = t.timestamp
  GROUP BY timestamp

答案 2 :(得分:0)

此查询应该有效:

SELECT timestamp, robo, COUNT(*) AS num_rows
FROM mytables
WHERE timestamp 
NOT IN (SELECT b.timestamp FROM mytables b
        JOIN (SELECT timestamp, count(*) FROM mytables
              WHERE robo = 'RE' 
              GROUP BY timestamp 
              HAVING COUNT(*) > 1) 
        a on a.timestamp = b.timestamp )
GROUP BY timestamp, robo

结果将是:

timestamp                  robo num_rows     
1518259341785               RE  1
1518259341785               A   3

我不确定您期望的结果是如何实现的。