简体   繁体   English

在 postgres 中分组

[英]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.在我的数据库中有一个名为 game_id 的列,我想根据 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.但是我有一个问题,我有 game_id 1999 和 game_id 19999 它们的值不同但它是同一个游戏。 I am looking for a solution on how to group these two game_id together.我正在寻找如何将这两个 game_id 组合在一起的解决方案。

在此处输入图像描述

You can change the value to the desired value in order to make your groupby statement work as you wish.您可以将该值更改为所需的值,以使您的 groupby 语句按您的意愿工作。

UPDATE table_name
SET game_id = 1999
WHERE game_id = 19999;

You can use case when and temp table您可以使用 case when 和 temp 表

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:如果这些是需要组合的特定游戏,您可以使用case表达式:

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.这对于替换多个game_id很方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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