Thursday, April 28, 2011

query for summing up values present in different columns in sql server 2005

i have columns i.e. theory marks, pratical marks, student's Id ,course Id ,& subject Id i need to add up the vaules present in columns theory marks & practical marks in order to get the aggregate, i dont know how to add the column values though. I am using sql server 2005

please help

From stackoverflow
  • assuming theory marks and practical marks are numerical data types

    SELECT
        student_id,
        course_id,
        subject_id,    
        SUM(theory_marks + practical_marks) AS overall_mark
    FROM
        table
    GROUP BY
        student_id, course_id, subject_id
    
    Sneha : thank you, that does solve my problem but just for curiousity sake, can you tell me how to do the same thing if the columns were of varchar datetype???
    Russ Cam : you need to CAST the column(s) to a numerical datatype. e.g. CAST(myVarCharColumn AS FLOAT). SQL Server will raise an error if a column value cannot be cast. See http://doc.ddart.net/mssql/sql70/ca-co_1.htm
    Russ Cam : You can check if a value is numeric before attempting to cast, using ISNUMERIC(myColumn).

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.