I am trying to create an expression in my SQL statement that SUMS the values for a given month for a given stock. I am not sure whether or not to use several SELECT statements as expressions or use a CASE WHEN statement. I would also like to SUM everything before the current year. For instance, if the current year was 2009, it was SUM everything purchased before 1/1/09. Here is what I have so far but cannot seem to get the syntax down:
Any thoughts? What is the most efficient way of going about this?Code:SELECT SUM(CASE sd_shares WHEN sd_date BETWEEN '1/1/2009' AND '1/31/2009' THEN sd_shares ELSE 0 END) As Month1, SUM(CASE sd_shares WHEN sd_date BETWEEN '2/1/2009' AND '2/28/2009' THEN sd_shares ELSE 0 END) As Month2, SUM(CASE sd_shares WHEN sd_date BETWEEN '3/1/2009' AND '3/31/2009' THEN sd_shares ELSE 0 END) As Month3, SUM(CASE sd_shares WHEN sd_date BETWEEN '4/1/2009' AND '4/30/2009' THEN sd_shares ELSE 0 END) As Month4, SUM(CASE sd_shares WHEN sd_date BETWEEN '5/1/2009' AND '5/31/2009' THEN sd_shares ELSE 0 END) As Month5, SUM(CASE sd_shares WHEN sd_date BETWEEN '6/1/2009' AND '6/30/2009' THEN sd_shares ELSE 0 END) As Month6, SUM(CASE sd_shares WHEN sd_date BETWEEN '7/1/2009' AND '7/31/2009' THEN sd_shares ELSE 0 END) As Month7, SUM(CASE sd_shares WHEN sd_date BETWEEN '8/1/2009' AND '8/31/2009' THEN sd_shares ELSE 0 END) As Month8, SUM(CASE sd_shares WHEN sd_date BETWEEN '9/1/2009' AND '9/30/2009' THEN sd_shares ELSE 0 END) As Month9, SUM(CASE sd_shares WHEN sd_date BETWEEN '10/1/2009' AND '10/31/2009' THEN sd_shares ELSE 0 END) As Month10, SUM(CASE sd_shares WHEN sd_date BETWEEN '11/1/2009' AND '11/30/2009' THEN sd_shares ELSE 0 END) As Month11, SUM(CASE sd_shares WHEN sd_date BETWEEN '12/1/2009' AND '12/31/2009' THEN sd_shares ELSE 0 END) As Month12 FROM tblStocks_detail WHERE s_id = 3



LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks