[英]How to convert nvarchar into int type for SQL Server
I tried to count the total the column [Trans Det Amt ex Tax] like the following:我试图计算 [Trans Det Amt ex Tax] 列的总数,如下所示:
SELECT
Loyalty_Type_Code,
COUNT([Loyalty_Number]),
FORMAT(SUM([Trans_Det_Amt_ex_Tax]), '##,###,###,##0')
FROM
CRM_POWERBI_RETAIL
WHERE
Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY
Loyalty_Type_Code
UNION
SELECT
'TOTAL',
COUNT(*) AS CCC,
COUNT(*) AS BBB
FROM
CRM_POWERBI_RETAIL
I get this error:我收到此错误:
Msg 245, Level 16, State 1, Line 39
消息 245,第 16 级,State 1,第 39 行
Conversion failed when converting the nvarchar value '67,527,726,031' to data type int.将 nvarchar 值 '67,527,726,031' 转换为数据类型 int 时转换失败。
So I tried to convert this to INT type by using the following:所以我尝试使用以下方法将其转换为 INT 类型:
SELECT
CONVERT(INT, Trans_Det_Amt_ex_Tax)
FROM
CRM_POWERBI_RETAIL
But the result still said但结果还是说
Conversion failed when converting the nvarchar value '67,527,726,031' to data type int
将 nvarchar 值 '67,527,726,031' 转换为数据类型 int 时转换失败
Please let me know how to fix this.请让我知道如何解决这个问题。
Thank you for all answers.感谢您的所有回答。
Don't convert the value to a string:不要将值转换为字符串:
SELECT Loyalty_Type_Code , COUNT([Loyalty_Number]),
SUM([Trans_Det_Amt_ex_Tax]))
FROM CRM_POWERBI_RETAIL
WHERE Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY Loyalty_Type_Code
UNION
SELECT 'TOTAL', COUNT(*) AS CCC, COUNT(*) AS BBB
FROM CRM_POWERBI_RETAIL;
All the types in a UNION ALL
need to be the same. UNION ALL
中的所有类型都必须相同。 If it sees a string and an integer -- as in the third column -- it will try to convert the string to an integer.如果它看到一个字符串和一个 integer(如第三列),它将尝试将字符串转换为 integer。 That is not possible with commas.
逗号是不可能的。
Alternatively, you can convert both columns to strings.或者,您可以将两列都转换为字符串。 A simpler method uses
GROUPING SETS
:更简单的方法使用
GROUPING SETS
:
SELECT COALESCE(Loyalty_Type_Code, 'Total'),
COUNT([Loyalty_Number]),
FORMAT(SUM([Trans_Det_Amt_ex_Tax]), '##,###,###,##0')
FROM CRM_POWERBI_RETAIL
WHERE Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY GROUPING SETS ( Loyalty_Type_Code, () );
select CONVERT(bigint, Trans_Det_Amt_ex_Tax)
int
cant hold number that big int
不能容纳那么大的数字
If you want to convert the value to a string, try removing the commas and using a data type cast that is large enough to store that data:如果要将值转换为字符串,请尝试删除逗号并使用足够大的数据类型转换来存储该数据:
SELECT CAST(REPLACE('67,527,726,031',',','') AS BIGINT);
This will strip the commas and store the data as a BIGINT
.这将去除逗号并将数据存储为
BIGINT
。
I'm not 100% sure, but you may need to CAST
the SUM
as a larger data type if you're going to be adding up a lot of values.我不是 100% 确定,但如果您要添加很多值,您可能需要将
CAST
SUM
为更大的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.