SQL GROUP BY有条件吗?

时间:2011-04-04 20:43:16

标签: mysql sql

我正在尝试将名为“CLOUD”的表复制到名为“t1_temp”的新表,同时根据名为“tag”的列对行进行分组。但我希望只有“NeighborhoodID”列相同时才会发生这种情况。

我正在运行的查询是:

INSERT INTO t1_temp (id, NeighborhoodID, power, tag) 
        SELECT id, NeighborhoodID, SUM(power), tag 
        FROM CLOUD GROUP BY tag ORDER BY NeighborhoodID

所以例如: enter image description here

第三个条目不应与第1个和第1个分组。第四个条目是因为“NeighborhoodID”不一样。

我希望我很清楚,如果没有请发表评论,谢谢。

3 个答案:

答案 0 :(得分:2)

您可以按多列进行分组,因此:

INSERT INTO t1_temp (id, NeighborhoodID, power, tag) 
    SELECT id, NeighborhoodID, SUM(power), tag 
    FROM CLOUD GROUP BY tag, NeighborhoodID ORDER BY NeighborhoodID

答案 1 :(得分:0)

我猜你的意思是将NeighborhoodID也添加到group by子句

    SELECT id, NeighborhoodID, SUM(power), tag 
    FROM CLOUD
    GROUP BY tag, NeighborhoodID
    ORDER BY NeighborhoodID

答案 2 :(得分:0)

INSERT INTO t1_temp (id, NeighborhoodID, power, tag) 
SELECT min(id), NeighborhoodID, SUM(power), tag 
FROM CLOUD 
GROUP BY NeighborhoodID, tag ORDER BY NeighborhoodID

这有帮助吗?