【问题标题】:Sql selecting distinct in whereSql在哪里选择不同的
【发布时间】:2021-10-19 11:16:51
【问题描述】:

我正在尝试进行总和选择:

select sum(price) as 'total', currency_id
from reports
group by currency_id

但是该表包含一个名为 transaction_id 的行,一旦计算了总和,我只想计算具有不同 transaction_id 值的行,我如何在哪里创建这个?

【问题讨论】:

  • 您能否分享示例数据和所需的输出
  • select sum(price) as 'total', currency_id, transaction_id from reports group by currency_id, transaction_id
  • 1) 提供示例数据和所需的输出 2) 标记您的数据库
  • 您能否阐明“计算具有不同 transaction_id 值的行”的意思?

标签: sql select


【解决方案1】:

如果你想对每个事务id计数一次,那么你可以使用窗口函数:

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_ids,你仍然可以使用窗口函数,但有区别:

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;

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 2022-08-18
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多