Wednesday, March 21, 2012

Question on SQL tables

Hi everyone,

I′m starting using SQL 2005 on visual studio 2005, and I have a question:

I have a table named employees in which I have 2 columns, one named "last used" which has the smalldatetime data type and the other named "salary" which has the decimal data type.

Now, I want to use a Select statement, to display in a new table 2 new columns, one with the sum of the salaries that correspond to the current month and the other with the sum of the values that belong to the previous month. I mean by this, all the salaries from july should be added up and be displayed in one column and all the ones from june should be added and displayed in the other column.

Can someone help me please?

Thanks in advance

Using this data set

LastUsed Salary 5/1/2007 0:00 150 5/1/2007 0:00 250 5/1/2007 0:00 350 6/1/2007 0:00 100 6/1/2007 0:00 200 6/1/2007 0:00 300 7/1/2007 0:00 50 7/1/2007 0:00 150 7/1/2007 0:00 250

..and this query

select

sum(case month(lastused) when month(getdate()) then salary end) as CurrentMonthSalary

,sum(case month(lastused) when month(getdate()) -1 then salary end) as PrevMonthSalary

from dbo.salary

...I return these results

CurrentMonthSalary PrevMonthSalary 450 600

I believe that's what you are looking for.

Tim

No comments:

Post a Comment