根据条件用不同的值更新 table

Update table with different values based on condition

我有一个 table,其中包含有关芝加哥不同社区区域的社会经济信息,例如无家可归者的百分比、贫困家庭的百分比等。现在我想做的是创建垃圾箱对于每个字段的值,如果百分比低于所有行的平均值,则该值设置为 0,而如果百分比等于或高于平均值,则设置为 1。

我想这样做,这样我就可以使用 bins 找到关联规则。

到目前为止,我提出了以下查询:

WITH avg AS (SELECT AVG(crowded_housing) AS ch from   
algorithms.socioeconomic_bins)
UPDATE algorithms.socioeconomic_bins SET crowded_housing=0 where     
crowded_housing<(SELECT ch FROM avg);

这本身有效,但由于我有 8 列我想分箱,我将不得不 运行 每个字段的查询两次(低于和高于平均值)。我找不到任何有用的页面或问题。有什么想法吗?

您可以像这样使用 CASE EXPRESSION:

WITH avg AS (SELECT AVG(crowded_housing) AS ch from   
algorithms.socioeconomic_bins)
UPDATE algorithms.socioeconomic_bins
SET crowded_housing= CASE WHEN crowded_housing < (SELECT ch FROM avg) 
                          THEN 0
                          ELSE 1
                     END

这将在一次查询中更新 table,并根据您的 WHERE 子句分配值。