好的,这里有。这一定是一件很容易的事情,但我所做的只是撕掉我那萎缩的头发!!!!
我有一个SQL查询:
Select A.ID,
A.field
(select vchr_Number from tbl_two B where B.int_ParentId = A.ID) as 'Number1',
(select vchr_Number from tbl_three C where C.int_ParentId = A.ID) as 'Number2',
(Number1 + Number2) as 'Number3'
From tbl_Something A
我要做的是将Number1和Numnber2加在一起。我确实需要返回所有三个值
由于两个值都是字符串,如果我只使用正常加法' +',它只会连接两个字符串,所以如果Number1 = 7而number2 = 8则Number3将是78而不是15。我尝试使用Cast命令将字符串转换为整数,不确定语法。
答案 0 :(得分:1)
您需要将数据转换为正确的数据类型(在下面的示例中,我使用INT):
SELECT T.*, CONVERT(INT, T.Number1) + CONVERT(INT, T.Number2) as 'Number3'
FROM (
SELECT A.ID, A.field,
(select vchr_Number
from tbl_two B
where B.int_ParentId = A.ID) as 'Number1',
(select vchr_Number
from tbl_three C
where C.int_ParentId = A.ID) as 'Number2',
From tbl_Something A
) AS T
或
SELECT A.ID, A.field,
(select CONVERT(INT, vchr_Number)
from tbl_two B
where B.int_ParentId = A.ID) +
(select CONVERT(INT, vchr_Number)
from tbl_three C
where C.int_ParentId = A.ID) as 'SumOfNumbers',
From tbl_Something A
注意:您需要将数据存储为其原始数据类型:数字作为数字,文本作为文本,日期作为日期等。切勿使用text / char,(n)varchar /存储数字或日期数据类型!
答案 1 :(得分:0)
Select A.ID,
A.field,(Number1 + Number2) as 'Number3'
From
(
Select A.ID,
A.field
(select vchr_Number from tbl_two B where B.int_ParentId = A.ID) as 'Number1',
(select vchr_Number from tbl_three C where C.int_ParentId = A.ID) as 'Number2',
(Number1 + Number2) as 'Number3'
From tbl_Something A
) T1