Pages

6 November 2013

SQL- Displaying all records from a table for last one year

Q. How to find all the records from a table for last one year ?

       A table named "Transactions" has the following transaction details.

Transactions
Suppose, we have to find all the records which has been transacted in the last one year. For this scenario we will make use of date field which is "DateOfTransaction" .The following below query in SQL Server will fetch the required results.


SELECT * FROM TRANSACTIONS 

WHERE DateOfTransaction > DATEADD(YYYY,-1,GETDATE())





Suppose we have to get total amount spent by each ID in last one year. The following below query will fetch the desired results.

SELECT ID,SUM(Amount) AS TotAmount FROM TRANSACTIONS 
WHERE DateOfTransaction > DATEADD(YYYY,-1,GETDATE())
GROUP BY ID


Similar scenario can be handled in ORACLE with slight changes in query.We will have to to use ADD_MONTHS instead of DATEADD and SYSDATE instead of GETDATE().

SELECT * FROM TRANSACTIONS
WHERE dateOftransaction > ADD_MONTHS(SYSDATE,-12);

SELECT ID,SUM(Amount) TotAmount FROM TRANSACTIONS
WHERE DateOfTransaction > ADD_MONTHS(SYSDATE,-12)
GROUP BY ID;








No comments:

Post a Comment