Recently I came across an interview
and I had been asked for write an SQL Query from the table for Month To Date
and Year To Date for sales amount from sales table.
Here is the synopsis:
If using Oracle use the trunc and numtoyminterval functions; if using SQL Server use the datediff function.
Oracle Month to Date:
Oracle Year to Date:
Oracle Rolling 12 Months:
Oracle Prior Year:
SQL Server Month to Date:
SQL Server Year to Date:
SQL Server Rolling 12 Months:
SQL Server Prior Year:
Hope it is useful.
Cheers!!!
Bose
Here is the synopsis:
If using Oracle use the trunc and numtoyminterval functions; if using SQL Server use the datediff function.
Oracle Month to Date:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE DATEOFSALES BETWEEN trunc(sysdate, 'MONTH') and sysdate |
Oracle Year to Date:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE DATEOFSALES BETWEEN trunc(sysdate, 'YEAR') and sysdate |
Oracle Rolling 12 Months:
select sum(SALES_AMOUNT) FROM SALES WHERE DATEOFSALES between trunc(sysdate - numtoyminterval(12, 'MONTH'), 'MONTH') and sysdate |
Oracle Prior Year:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE trunc(DATEOFSALES, 'YEAR') = trunc(sysdate - numtoyminterval (1, 'YEAR'), 'YEAR') |
SQL Server Month to Date:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE datediff(month, DATEOFSALES, getdate()) = 0 AND DATEOFSALES <= getdate() |
SQL Server Year to Date:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE datediff(year, DATEOFSALES, getdate()) = 0 AND DATEOFSALES <= getdate() |
SQL Server Rolling 12 Months:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE datediff(month, DATEOFSALES, getdate()) <= 12 AND DATEOFSALES <= getdate() |
SQL Server Prior Year:
SELECT sum(SALES_AMOUNT) FROM SALES WHERE datediff(year, DATEOFSALES, getdate()) = 1 |
Hope it is useful.
Cheers!!!
Bose
Thanks for sharing this clear SQL
ReplyDelete