简体   繁体   中英

sql quest with amount and exchange rate

How to choose customers who have made a large amount of payments in December 2018 if we take into account the exchange rate

I have a table:

  • Trandate date - transaction date
  • Transum numeric (20,2) - amount of payment
  • CurrencyRate numeric (20,2) - currency exchange rate


 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

but I think that "max" is not at all what I need

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

I need something this

ID_Client   Transum 
   3         1750

Where 1750 is a "UAH" and 350USD + 300UAH + 250EUR, exchange rate of USD is 2, exchange rate of EUR is 3.

I think you want sum() . Then you can order by the result:

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;

If you're trying to get the sum of transaction amounts by client for the year 2018 and month of December, you could write it like this:

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

If you want things grouped by each client, year, and month in a given date range, you'd write it like this:

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)

I added a column name for your computed column so that the result set is still relational (columns need distinct names).

I'd recommend reading up on the SQL 'group by' clause ( https://www.w3schools.com/sql/sql_groupby.asp ) and aggregate ( https://www.w3schools.com/sql/sql_count_avg_sum.asp , https://www.w3schools.com/sql/sql_min_max.asp ) operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM