简体   繁体   中英

grouping by in postgres

In my database there is a column named game_id, I want to sum the other values based on the group by game_id. But I have a problem that I have game_id 1999 and game_id 19999 their values are different but It is same game. I am looking for a solution on how to group these two game_id together.

在此处输入图像描述

You can change the value to the desired value in order to make your groupby statement work as you wish.

UPDATE table_name
SET game_id = 1999
WHERE game_id = 19999;

You can use case when and temp table

IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#LocalTempTablo%') 
BEGIN
   DROP TABLE #LocalTempTablo;
END;

CREATE TABLE #LocalTempTablo
(
    game_id int, 
    sumexample int
)

INSERT INTO #LocalTempTablo SELECT CASE WHEN game_id=1999 or game_id=19999 THEN 1999 ELSE 1999 END, SUM(sumexample) FROM games WHERE game_id=1999 or game_id=19999
GROUP BY game_id

SELECT game_id, SUM(sumexample) FROM #LocalTempTablo
GROUP BY game_id

If these are the specific games that need to be combined you can use a case expression:

select (case when game_id = 19999 then 1999 else game_id end) as imputed_game_id,
       sum(score)  -- or whatever
from t
group by imputed_game_id;

You can also handle this with a replacement table -- perhaps built directly into the query:

select coalesce(v.new_game_id, t.game_id) as imputed_game_id,
       . . .
from t left join
     (values (19999, 1999)
     ) v(game_id, new_game_id)
     on t.game_id = v.game_id
group by imputed_game_id;

This is handy for replacing multiple game_id s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM