根据 SQL 中的其他字段创建具有条件值的字段

Create a field with conditional values based on other fields in SQL

我有一个 table 这样的:

ID Revenue_Tom Revenue_John Revenue_Lisa
aaa 0 257 138
aab 376 0 0

我需要创建一个 table,其中 ID 字段是旧 ID 的值 + 没有 0 值的字段的名称。 如果一个ID有超过2个非零值的字段,我需要分别创建2个新的ID,并且我需要Revenue字段是每个情况下已经考虑过的旧收入的值。

这就是预期的输出(有点难以解释,我认为预期的输出更不言自明):

ID2 Revenue
aaa_John 257
aaa_Lisa 138
aab_Tom 376

(我在使用 SQL+Jinja 的 DBT 中这样做)

如果您创建 3 个查询并加入 with union all,您将得到您的结果。

SELECT CONCAT(ID,'_Tom') ID2
   Revenue_Tom Revenue
FROM table_name
WHERE Revenue_Tom > 0
   UNION ALL
SELECT CONCAT(ID,'_John') ID2
   Revenue_John
FROM table_name
WHERE Revenue_John > 0
   UNION ALL
SELECT CONCAT(ID,'_Lisa') ID2
   Revenue_Lisa
FROM table_name
WHERE Revenue_Lisa > 0;