我正在尝试迭代函数内部的临时表,我希望在每一行都进行更新。
临时表应该包含从查询中获取的所有用户ID。 之后,如果具有属性的交易百分比小于所有交易的50%,则应检查每个单个用户。
最后,应更新帐户字段master_segments。
我的代码看起来像这样:
CREATE OR REPLACE FUNCTION temptable()
RETURNS VARCHAR
AS $$
BEGIN
CREATE TEMP TABLE IF NOT EXISTS testTable AS
SELECT account.sfid, transactions.transactionNumber
FROM account
INNER JOIN transactions ON account.sfid =transactions.accountsfid
INNER JOIN transactionLineItems ON transactions.transactionNumber = transactionLineItems.transactionNumber
INNER JOIN products ON transactionLineItems.USIM = products.USIM
WHERE account.gender = '1' AND (transactions.transactionDate >= current_date - interval '730' day AND products.gender = 'female' AND products.agegroup = 'adult');
FOR j IN testTable.sfid LOOP
SELECT(
(SELECT COUNT(transactions.transactionNumber)
FROM transactions
INNER JOIN account ON account.sfid = transactions.accountsfid
INNER JOIN transactionLineItems ON transactions.transactionNumber = transactionLineItems.transactionNumber
INNER JOIN products ON transactionLineItems.USIM = products.USIM
WHERE products.gender = 'male' AND products.agegroup = 'adult' AND transactions.transactionDate >= current_date - interval '730' day)*1.0 /
(SELECT COUNT(transactions.transactionNumber)
FROM transactions
WHERE transactions.transactionDate >= current_date - interval '730' day)
) < 0.5;
UPDATE account
SET account.master_segments = 'Women' WHERE account.sfid = testTable.sfid;
END LOOP;
END;
$$ LANGUAGE plpgsql;
我收到此消息:
ERROR: syntax error at or near "testTable"
LINE 14: FOR j IN testTable.sfid LOOP
有人对此有建议吗? 谢谢!
答案 0 :(得分:0)
我假设你尝试做的是:
UPDATE account
SET account.master_segments = 'Women'
FROM (
SELECT account.sfid, transactions.transactionNumber
FROM account
INNER JOIN transactions ON account.sfid =transactions.accountsfid
INNER JOIN transactionLineItems ON transactions.transactionNumber = transactionLineItems.transactionNumber
INNER JOIN products ON transactionLineItems.USIM = products.USIM
WHERE account.gender = '1' AND (transactions.transactionDate >= current_date - interval '730' day AND products.gender = 'female' AND products.agegroup = 'adult')
) testtable
WHERE account.sfid = testtable.sfid
答案 1 :(得分:0)
您不需要子查询,也不需要为此逻辑重复account
表:
UPDATE account a
SET master_segments = 'Women'
FROM transactions t INNER JOIN
transactionLineItems tli
ON t.transactionNumber = tli.transactionNumber AND
t.transactionDate >= current_date - interval '730' day INNER JOIN
products p
ON tli.USIM = p.USIM AND
p.gender = 'female' AND
p.agegroup = 'adult'
WHERE a.gender = '1' AND a.sfid = t.sfid;
我还引入了表别名,因此查询更容易编写和阅读。