为了将各种货币的金额转换为美元,我想要使用以下查询:
SELECT
currency,
CASE currency
WHEN 'SAR' THEN 0.266
WHEN 'EGP' THEN 0.113
WHEN 'USD' THEN 1
WHEN 'JOD' THEN 1.411
WHEN 'GBP' THEN 1.311
WHEN 'BHD' THEN 2.652
WHEN 'AED' THEN 0.272
WHEN 'EUR' THEN 1.111
WHEN 'QAR' THEN 0.275
WHEN 'KWD' THEN 3.315
ELSE 0
END as in_usd,
SUM(amount)*in_usd as total_in_usd
FROM
mytable
WHERE
created_at >= current_date - '7 days'::INTERVAL
GROUP BY
currency
此操作失败,显示消息in_usd does not exist
。
预期产出是一系列货币及其总数:
currency total_in_usd
USD 100.00
AED 59.00
GBP 143.01
...
答案 0 :(得分:4)
将CASE
表达式部分放在派生表中。对其GROUP BY
做出结果:
select currency, in_usd, SUM(amount) * in_usd as total_in_usd
from
(
SELECT
currency,
CASE currency
WHEN 'USD' THEN 1
WHEN 'SAR' THEN 0.266
WHEN 'EGP' THEN 0.113
WHEN 'USD' THEN 1
WHEN 'JOD' THEN 1.411
WHEN 'GBP' THEN 1.311
WHEN 'BHD' THEN 2.652
WHEN 'AED' THEN 0.272
WHEN 'EUR' THEN 1.111
WHEN 'QAR' THEN 0.275
WHEN 'KWD' THEN 3.315
ELSE 0
END as in_usd,
amount
FROM
mytable
WHERE
created_at >= current_date - '7 days'::INTERVAL
)
GROUP BY
currency, in_usd
答案 1 :(得分:2)
你几乎拥有正确的结构 - 一个小调整应该让它工作得很好。在进行总和时乘以货币转换 -
SELECT
currency,
SUM(amount)*
(CASE currency
WHEN 'SAR' THEN 0.266
WHEN 'EGP' THEN 0.113
WHEN 'USD' THEN 1
WHEN 'JOD' THEN 1.411
WHEN 'GBP' THEN 1.311
WHEN 'BHD' THEN 2.652
WHEN 'AED' THEN 0.272
WHEN 'EUR' THEN 1.111
WHEN 'QAR' THEN 0.275
WHEN 'KWD' THEN 3.315
ELSE 0
END) as total_in_usd
FROM
mytable
WHERE
created_at >= current_date - '7 days'::INTERVAL
GROUP BY
currency
答案 2 :(得分:1)
在解析整个目标列表之前,无法识别别名,这意味着您无法在目标列表中的其他位置引用别名。例如,以下语句将失败:
select (qtysold + 1) as q, sum(q) from sales group by 1;
ERROR: column "q" does not exist
您可以使用子选项修复此问题:
SELECT inner.currency, inner.in_usd, inner.sum_amount*inner.in_usd as total_in_usd
from (
SELECT
currency,
CASE currency
WHEN 'SAR' THEN 0.266
WHEN 'EGP' THEN 0.113
WHEN 'USD' THEN 1
WHEN 'JOD' THEN 1.411
WHEN 'GBP' THEN 1.311
WHEN 'BHD' THEN 2.652
WHEN 'AED' THEN 0.272
WHEN 'EUR' THEN 1.111
WHEN 'QAR' THEN 0.275
WHEN 'KWD' THEN 3.315
ELSE 0
END as in_usd,
SUM(amount) as sum_amount
FROM
mytable
WHERE
created_at >= current_date - '7 days'::INTERVAL
GROUP BY
currency) inner