簡體   English   中英

使用CASE WHEN從單獨的行中獲取單獨的值

[英]Getting separate values from separate rows using CASE WHEN

我有一個數據集,其中用戶有2個動作,一個有用的動作和一個無用的動作:

user_id | action_id | useful
   1    |     3     |  True
   1    |     4     |  False
   2    |     5     |  True

我想要一個數據集,該數據集顯示用戶ID,以及他們在同一行上執行的有用和無效操作的ID。 像這樣:

user_id | useful_action_id | not_useful_action_id
   1    |       3          |         4
   2    |       5          |       NULL

我嘗試了以下方法:

SELECT
    user_id,
    case when useful = True then action_id else null end,
    case when useful = False then action_id else null end
FROM actions
GROUP BY user_id

但有人告訴我:

Error running query: column "useful" must appear in the `GROUP BY` clause or be used in an aggregate function

但是,不,我特別不希望“有用”出現在GROUP BY對嗎? 我只希望將其按user_id分組

您正在使用GROUP BY ,但不執行任何聚合。 看起來您正在嘗試有條件的聚合,並且非常接近。 您只需要使用聚合函數,如下所示:

SELECT
    user_id,
    max(case when useful = True then action_id end) AS useful_action_id,
    max(case when useful = False then action_id end) AS not_useful_action_id
FROM actions
GROUP BY user_id

如果要為每個用戶擁有“有用的”和“無效的” ID,請使用array_agg()聚合函數:

select
    user_id,
    array_agg(action_id) filter (where useful) as useful_action_ids,
    array_agg(action_id) filter (where not useful) as not_useful_action_ids
from actions
group by 1;

幾個附加的評論:

  • 如果在組中沒有找到ID,它將輸出空數組( {} ),而不是NULL。 如果確實需要NULL,請添加case / when表達式。
  • 如果useful列中包含NULL,則上面的查詢將不會使用它們。 在這種情況下,如果您確實希望將這些NULL視為“無用”,則只需使用(where not coalesce(useful, false)) 但可能您會更喜歡使用一組ID,例如,帶有filter (where useful is null) usefulness_is_not_clear filter (where useful is null) :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM