转换varchar值

时间:2018-11-23 15:28:04

标签: sql sql-server sql-server-2016

我正在尝试计算两个表中相同的值,并且似乎在第一行中遇到错误。

select 
    count(substring(c.source_code, 3, 4)) comb,  ---->Error
    count(os.CompanyCode) comcode 
from 
    combined c
inner join 
    Completes os on os.companycode = substring(c.source_code,3,4)
where 
    os.ReturnYearFiled = 2017
    and c.return_year = 2017

错误:

  

将varchar值'SH'转换为数据类型int时转换失败

数据集:

Combined.sourcecode                      Completes.companycode
-------------------                      ---------------------
  01582365                                 5823  
  14785698                                 7856
  45879652                                 8796
  87459633                                 4596 
  14563344                                 5633

请求的结果:

 comb                              comcode
 ------------------------------------------
   5                                 5

2 个答案:

答案 0 :(得分:2)

我认为CompanyCode或Source_code具有字母数字数据。因此,您会收到错误消息。

我已经更新了您的脚本,应该没问题:

SELECT
    COUNT(SUBSTRING(c.source_code, 3, 4)) comb
   ,COUNT(os.CompanyCode) comcode
FROM combined c
INNER JOIN Completes os
    ON CAST(os.companycode AS VARCHAR(100)) = CAST(SUBSTRING(c.source_code, 3, 4) AS VARCHAR(100))
WHERE os.ReturnYearFiled = 2017
AND c.return_year = 2017

此外,如果要检查哪些值是字母数字,可以使用ISNUMERIC

SELECT * FROM combined WHERE IsNumeric(source_code)=0
SELECT * FROM Completes WHERE IsNumeric(source_code)=0

答案 1 :(得分:1)

如果您需要不为空的商品数量,则可以使用:

select sum(case when c.source_code is not null then 1 else 0 end) combCount,  
sum(case when os.CompanyCode is not null then 1 else 0 end) comcodeCount,
substring(c.source_code,3,4) comb,  
os.CompanyCode as comcode  
from combined c
inner join Completes os on os.companycode = substring(c.source_code,3,4)
where os.ReturnYearFiled = 2017
and c.return_year = 2017
group by substring(c.source_code,3,4),os.CompanyCode

或者如果您只需要记录数:

select count(*) as records, substring(c.source_code,3,4) comb,  
os.CompanyCode as comcode 
from combined c
inner join Completes os on os.companycode = substring(c.source_code,3,4)
where os.ReturnYearFiled = 2017
and c.return_year = 2017
group by substring(c.source_code,3,4),os.CompanyCode