Search code examples
sql-server-2008t-sqlcastingintnvarchar

T-SQL Casting From Nvarchar to Int


I want to order some data and I need to enter the total number at the end of the table. But the problem is since the name of the total must be total(it is a homework and it has to be identical) I need to cast weeeks as nvarchar. The problem is that when I do that, it does not sort the data properly. How Can I fix this?

select CASE GROUPING(Weeks) WHEN 1 THEN 'Total' ELSE Weeks END as Weeks, SUM(Goals) as Total_Goals
from 
(
        SELECT Cast([Week] AS NVARCHAR(50)) as Weeks, SUM([Home Score]) as Goals from Fixture
        group by [Week]
        union
        SELECT Cast([Week] AS NVARCHAR(50)) as Weeks, SUM([Away Score]) as Goals from Fixture 
        group by [Week]

) as tblGoals
group by Weeks with ROLLUP
order by Weeks

The Data:

 Weeks  Total_Goals
1   33
10  32
11  47
12  29
13  20
14  28
15  37
16  29
17  37
18  32
19  35
2   33
20  33
21  37
22  14
23  43
24  33
25  28
26  32
27  35
28  44
29  43
3   31
30  39
31  43
32  35
33  42
34  37
4   37
5   34
6   39
7   20
8   29
9   33
Total   1153

Solution

  • Since you converted weeks to nvarchar, it's being sorted alphabetically, not numerically.

    When you order by weeks, convert it back to int.

    order by cast(Weeks as int)