Tom
Tom

Reputation: 9643

SQL GROUP BY with a condition?

I'm trying to copy a table named "CLOUD" to a new one named "t1_temp" while grouping the rows based on a column named "tag". BUT i want this to happen only if the "NeighborhoodID" column is the same.

The query i'm running is:

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

So for example: enter image description here

The third entry shouldn't be grouped with the 1th & 4th entry's because the "NeighborhoodID" isn't the same.

I hope i'm clear, if not please comment, thanks.

Upvotes: 4

Views: 9406

Answers (3)

shahkalpesh
shahkalpesh

Reputation: 33476

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

Does this help?

Upvotes: 0

amit_g
amit_g

Reputation: 31250

I guess you mean to add NeighborhoodID also to the group by clause

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

Upvotes: 0

Wrikken
Wrikken

Reputation: 70460

You can group by multiple columns, so:

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

Upvotes: 2

Related Questions