在 WHERE 子句中使用类似 WINDOW 的函数对表进行 SQL 更新
Posted
技术标签:
【中文标题】在 WHERE 子句中使用类似 WINDOW 的函数对表进行 SQL 更新【英文标题】:SQL updates to table using WINDOW-like function in WHERE clause 【发布时间】:2019-07-24 05:00:42 【问题描述】:我有一份按代表、客户、交易编号汇总销售交易的报告,如果总部已与他们联系以查看他们是否需要其他帮助,则标记为标记。当我提取数据时,我可以看到一些销售代表在同一个帐户中进行了多项交易。
这是报告的示例。在此示例中,已联系过销售代表 A,但从未联系过销售代表 B。我们要填写销售代表 A 已联系的字段,同时将销售代表 B 保留为
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Sales rep A | 1
Sales rep A | account 2 | <null> | 2
Sales rep A | account 1 | <null> | 3
Sales rep B | account a | <null> | 1
Sales rep B | account b | <null> | 2
...
我想使用“销售代表 A”(或“是”)更新已联系的列 所以它看起来像这样:
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Yes | 1
Sales rep A | account 2 | Yes | 2
Sales rep A | account 1 | Yes | 3
Sales rep B | account a | <null> | 1
Sales rep B | account b | <null> | 2
...
对我来说,这看起来像是一个窗口函数的例子,但也许自联接会更好。我试图弄清楚 select 函数会是什么样子
SELECT "opportunity owner", "contacted", "Account", "deal no."
DENSE_RANK () OVER (PARTITION by
--"opportunity owner"
(SELECT "opportunity owner" FROM "test_weekly_top_deal_report" WHERE "worked with this rep before?" LIKE 'Sales rep A')) AS "rank"
FROM "test_weekly_top_deal_report"
WHERE "opportunity owner" LIKE 'Sales rep A'
这给了我:
opportunity owner | Account | contacted | deal no.
--------------------------------------------------------
Sales rep A | account 1 | Sales rep A | 1
Sales rep A | account 2 | <null> | 2
Sales rep A | account 1 | <null> | 3
但是当我修改它以运行 所有 代表时,我使用了这个:
SELECT "opportunity owner", "worked with this rep before?", "account name",
DENSE_RANK () OVER (PARTITION by
--"opportunity owner"
(SELECT "opportunity owner" FROM "test_weekly_top_deal_report" WHERE "worked with this rep before?" NOT LIKE 'NO')) AS "rank"
FROM "test_weekly_top_deal_report"
WHERE 子句中的小改动现在变为“NOT LIKE 'NO'”。那只是给了我一个错误:
The database reported a syntax error: [Amazon](500310) Invalid operation:
Invalid Query: Details: ----------------------------------------------- error:
Invalid Query: code: 8001 context: single-row subquery returns more than one row query: 2151115 location: 0.cpp:8
建议?我如何让这个迭代所有的代表,从而填写“联系”列?
【问题讨论】:
【参考方案1】:select ("opportunity owner" from "test_weekly_top_deal_report"
where "contacted" is "opportunity owner") as X;
select case
when ("opportunity owner" in (X)) and ("contacted" is null or "contacted" is "opportunity owner")
then 'Yes'
else 'No' as contacted
from "test_weekly_top_deal_report"
【讨论】:
感谢@ketcham 的回复。我在请求中并不清楚。我只想更新那些已联系过的代表。所以逻辑有点复杂 - 如果每个代表的任何一行不为空,则将所有联系的行设置为代表的名称。对所有代表重复。我更新了示例表以更清晰。 啊,我明白了——刚刚编辑过。不幸的是,我目前无法对此进行测试,但这应该符合您的需求以上是关于在 WHERE 子句中使用类似 WINDOW 的函数对表进行 SQL 更新的主要内容,如果未能解决你的问题,请参考以下文章