我有一个名为'companyInfo'的表,并且'Amount'的数据类型为nvarchar
,样本数据如下:
companyInfo
IDs | company | year | Amount
----+-----------+------+-------
1 | Company A | 2011 | 40.00
2 | Company B | 2011 | Null
2 | Company C | 2011 | 100.00
4 | Company D | 2011 | 205.11
5 | Company E | 2011 | 0
6 | Company F | 2011 | Null
我写了如下查询:
select IDs
, company
, sum(ISNULL(CAST(Amount AS MONEY), 0)) Amount
, year
from companyInfo
where Amount is not null
and year(cast(year as date)) = '2018'
group by IDs
, company
, Amount
, year
得到以下错误:
错误:
消息235,级别16,状态0,第27行 无法将char值转换为金钱。 char值的语法错误。
答案 0 :(得分:0)
可能是因为您的区域设置。 请检查:
select
IDs
,company
,sum(ISNULL(CAST(REPLACE(Amount, '.', ',') AS MONEY),0)) Amount
,year
from companyInfo
where Amount is not null
and year(cast(year as date)) = '2018'
group by IDs,company,Amount,year;
您可以通过运行以下命令来调试失败原因:
SELECT CAST(REPLACE('205.11', '.', ',') AS MONEY),0)
或
SELECT CAST('205.11'AS MONEY)
找出问题所在
答案 1 :(得分:0)
这就是您想要的。两个查询都提供相同的结果
样式1
SELECT IDs
,Company
,FORMAT(YearFormed, 'yyyy') AS YearFormed
,Amount
FROM
(SELECT C.IDs, C.Company, CONVERT(DATE, C.YearFormed) AS YearFormed, CONVERT(MONEY, C.Amount) AS Amount FROM temp.dbo.CompanyInfo AS C) AS RC
WHERE Amount IS NOT NULL
样式2
WITH RESULT AS --3-I named this query with the intention to formart the Year in which the companies were formed
(
SELECT IDs --1-Started from here
,Company
,CONVERT(DATE, C.YearFormed) AS YearFormed --2-I converted to Date here so I couldnt run format too so
,CONVERT(MONEY, C.AMOUNT) AS Amount
FROM temp.dbo.CompanyInfo AS C
WHERE C.AMOUNT IS NOT NULL
)
SELECT R.IDs
,R.Company
,FORMAT(R.YearFormed, 'yyyy') AS YearFormed --4-I used this SELECT statement only to format this column
,R.Amount
FROM RESULT AS R
这就是结果