T-SQL 从 Nvarchar 转换为 Int
T-SQL Casting From Nvarchar to Int
我想订购一些数据,需要在table最后输入总数。但问题是因为总计的名称必须是总计(这是一项作业并且必须相同)我需要将 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”将值填充为 2。
select REPLACE(STR(CAST(weeks AS Varchar(2)), 2), SPACE(1), '0')
由于您将周数转换为 nvarchar,因此它按字母顺序而不是数字顺序排序。
按周排序时,将其转换回整数。
order by cast(Weeks as int)
以下查询将解决您的问题。
创建table#Schedule(周整数,Total_Goals整数)
插入#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') as Weeks, SUM(Total_Goals) as Goals from #Schedule
使用 ROLLUP
按 [Weeks] 分组
我想订购一些数据,需要在table最后输入总数。但问题是因为总计的名称必须是总计(这是一项作业并且必须相同)我需要将 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”将值填充为 2。
select REPLACE(STR(CAST(weeks AS Varchar(2)), 2), SPACE(1), '0')
由于您将周数转换为 nvarchar,因此它按字母顺序而不是数字顺序排序。
按周排序时,将其转换回整数。
order by cast(Weeks as int)
以下查询将解决您的问题。
创建table#Schedule(周整数,Total_Goals整数)
插入#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') as Weeks, SUM(Total_Goals) as Goals from #Schedule 使用 ROLLUP
按 [Weeks] 分组