Sql 选择不同的地方
Sql selecting distinct in where
我正在尝试求和 select:
select sum(price) as 'total', currency_id
from reports
group by currency_id
但是 table 包含一个名为 transaction_id 的行,一旦计算总和我想只计算具有不同 transaction_id 值的行,我如何创建它在哪里?
如果你想对每个交易id统计一次,那么你可以使用window函数:
select sum(price) as total, currency_id
from (select r.*,
row_number() over (partition by transaction_id order by transaction_id) as seqnum
from reports r
) r
where seqnum = 1
group by currency_id;
如果你想对只出现一次的 transaction_id
求和,你仍然可以使用 window 函数,但有一个区别:
select sum(price) as total, currency_id
from (select r.*,
count(*) over (partition by transaction_id) as cnt
from reports r
) r
where cnt = 1
group by currency_id;
我正在尝试求和 select:
select sum(price) as 'total', currency_id
from reports
group by currency_id
但是 table 包含一个名为 transaction_id 的行,一旦计算总和我想只计算具有不同 transaction_id 值的行,我如何创建它在哪里?
如果你想对每个交易id统计一次,那么你可以使用window函数:
select sum(price) as total, currency_id
from (select r.*,
row_number() over (partition by transaction_id order by transaction_id) as seqnum
from reports r
) r
where seqnum = 1
group by currency_id;
如果你想对只出现一次的 transaction_id
求和,你仍然可以使用 window 函数,但有一个区别:
select sum(price) as total, currency_id
from (select r.*,
count(*) over (partition by transaction_id) as cnt
from reports r
) r
where cnt = 1
group by currency_id;