Skip to content
Advertisement

Join two columns as a date in sql

I am currently working with a report through Microsoft Query and I ran into this problem where I need to calculate the total amount of money for the past year.

The table looks like this:

Item Number | Month | Year | Amount |
...........PAST YEARS DATA...........
  12345     |   1   | 2019 |   10   |
  12345     |   2   | 2019 |   20   |
  12345     |   3   | 2019 |   15   |
  12345     |   4   | 2019 |   12   |
  12345     |   5   | 2019 |   11   |
  12345     |   6   | 2019 |   12   |
  12345     |   7   | 2019 |   12   |
  12345     |   8   | 2019 |   10   |
  12345     |   9   | 2019 |   10   |
  12345     |   10  | 2019 |   10   |
  12345     |   11  | 2019 |   10   |
  12345     |   12  | 2019 |   10   |
  12345     |   1   | 2020 |   10   |
  12345     |   2   | 2020 |   10   |

How would you calculate the total amount from 02-2019 to 02-2020 for the item number 12345?

Advertisement

Answer

Assuming that you are running SQL Server, you can recreate a date with datefromparts() and use it for filtering:

select sum(amount)
from mytable
where 
    itemnumber = 12345
    and datefromparts(year, month, 1) >= '20190201'
    and datefromparts(year, month, 1) < '20200301'
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement