【问题标题】:sql quest with amount and exchange ratesql查询金额和汇率
【发布时间】:2019-10-03 18:14:31
【问题描述】:

如果考虑汇率,如何选择2018年12月大额付款的客户

我有一张桌子:

  • 交易日期 - 交易日期
  • 传输数字 (20,2) - 支付金额
  • CurrencyRate numeric (20,2) - 货币汇率


 ID_Client  Trandate    Transum CurrencyRate    Currency
 --------------------------------------------------------
 1          2018.12.01  100     1               UAH
 1          2018.12.02  150     2               USD
 2          2018.12.01  200     1               UAH
 3          2018.12.01  250     3               EUR
 3          2018.12.02  300     1               UAH
 3          2018.12.03  350     2               USD
 7          2019.01.08  600     1               UAH

但我认为“max”根本不是我需要的

 SELECT ID_Client, MAX(Transum*CurrencyRate) 
 FROM `Payment.TotalPayments` 
 WHERE YEAR(Trandate) = 2018
       AND MONTH(Trandate) = 12

我需要这个

ID_Client   Transum 
   3         1750

其中 1750 是“UAH”,350USD + 300UAH + 250EUR,美元汇率为 2,欧元汇率为 3。

【问题讨论】:

  • 从您的示例数据中,预期的输出是什么?可以加一下吗?
  • 好的,如何将其计入汇率?
  • ID_CLIENT - 3 Transum - 1000UAH 其中 transum = 300uah+350usd
  • 为什么250EUR250*3 不包含在预期输出中的ID_Client 3 中?意思是每个客户的前2个最高Transum只考虑计算?
  • 抱歉更正

标签: sql sql-server-2005


【解决方案1】:

我想你想要sum()。然后你可以order by结果:

SELECT ID_Client, SUM(Transum*CurrencyRate) as total 
FROM `Payment.TotalPayments` 
WHERE Trandate >= '2018-12-01' AND Transdate < '2019-01-01'
GROUP BY ID_Client
ORDER BY total DESC;

【讨论】:

    【解决方案2】:

    如果您想获取客户在 2018 年和 12 月的交易金额总和,您可以这样写:

    SELECT ID_Client, SUM(Transum*CurrencyRate) as payment_total_converted
    FROM `Payment.TotalPayments` 
    WHERE YEAR(Trandate) = 2018
    and MONTH(Trandate) = 12
    group by ID_Client
    

    如果您希望在给定日期范围内按每个客户、年份和月份对事物进行分组,您可以这样写:

    SELECT ID_Client, YEAR(Trandate) as tran_year, MONTH(Trandate) as tran_month, 
    SUM(Transum*CurrencyRate) as payment_total_converted
    FROM `Payment.TotalPayments` 
    WHERE Trandate between '2018-12-01' and '2019-01-01'
    group by ID_Client, YEAR(Trandate), MONTH(Trandate)
    

    我为您的计算列添加了一个列名,以便结果集仍然是相关的(列需要不同的名称)。

    我建议阅读 SQL 'group by' 子句 (https://www.w3schools.com/sql/sql_groupby.asp) 和聚合 (https://www.w3schools.com/sql/sql_count_avg_sum.asp, https://www.w3schools.com/sql/sql_min_max.asp) 运算符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2019-07-22
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多