金额和汇率的SQL任务

时间:2019-05-16 12:51:05

标签: sql sql-server-2005

如果考虑汇率,如何选择在2018年12月支付了大笔款项的客户

我有一张桌子:

  • 最后日期-交易日期
  • 数字转帐(20,2)-付款金额
  • CurrencyRate数字(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,USD的汇率是2,EUR的汇率是3。

2 个答案:

答案 0 :(得分:0)

我认为您想要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;

答案 1 :(得分:0)

如果您尝试按客户获取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.asphttps://www.w3schools.com/sql/sql_min_max.asp)运算符。