2011-04-04 89 views
4

我試圖將名爲「CLOUD」的表複製到名爲「t1_temp」的新表中,同時基於名爲「tag」的列對行進行分組。但我希望只有在「NeighborhoodID」列相同時纔會發生這種情況。SQL GROUP BY有條件嗎?

我運行查詢:

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號&第4項的分組,因爲「NeighborhoodID」 ISN」同樣的。

我希望我很清楚,如果不是請評論,謝謝。

回答

2

您可以通過多個列組,所以:

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

豎起@Wrikken謝謝! – Tom 2011-04-04 20:49:17

0

我猜你的意思是還by子句

SELECT id, NeighborhoodID, SUM(power), tag 
    FROM CLOUD 
    GROUP BY tag, NeighborhoodID 
    ORDER BY NeighborhoodID 
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 

這是否幫助添加NeighborhoodID到組?

+0

它@shahkalpesh!我必須標記@Wrikken,因爲他首先回答,但非常感謝您的回覆。 – Tom 2011-04-04 20:54:17