I am attempting to develop an SQL field that is the sum of all columns for the row excluding the first two. Below is my code, which returns columns MonthYear, Total, Sum1, Sum2, and Sum3. I’d like to have a FinalSum which totals Sum1,Sum2, and Sum3. This is to be used to counter check the Total column for accuracy. Is there a way to do this? Running Microsoft SQL Server 2005 – T-SQL
SELECT MonthYear,
COUNT(*) AS Total,
ISNULL(
SUM(
CASE
WHEN Status='Sum1' THEN 1
ELSE 0
END
)
,0) AS [Sum1],
ISNULL(
SUM(
CASE
WHEN Status='Sum2' THEN 1
ELSE 0
END
)
,0) AS [Sum2],
ISNULL(
SUM(
CASE
WHEN Status='Sum3' THEN 1
ELSE 0
END
)
,0) AS [Sum3]
FROM tablename
GROUP BY
MonthYear
You are missing a
FROMon your query. Anyway, one way would be using a derived table:For SQL Server 2005+, you can also use CTEs: