我想订购一些数据,我需要输入表格末尾的总数。但问题是因为总数的名称必须是总数(这是一项功课,而且必须相同)我需要将weeeks作为nvarchar。问题是,当我这样做时,它不会正确排序数据。我该如何解决这个问题?
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
数据:
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
答案 0 :(得分:0)
由于您将周转换为nvarchar,因此按字母顺序排序,而不是数字排序。
按周订购时,请将其转换回int。
order by cast(Weeks as int)
答案 1 :(得分:0)
以下查询将解决您的问题。
创建表#Schedule(Weeks int,Total_Goals int)
插入#Schedule值 (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) - 总计1153
SELECT Isnull(Cast([Weeks] AS NVARCHAR(50)),' Total')作为周,SUM(Total_Goals)作为来自#Schedule的目标 分组[周]与ROLLUP