SQL Server 2005 - 出于未知原因获取错误

时间:2010-08-17 13:25:20

标签: sql tsql sql-server-2005

我要做的是创建一个包含2个字段的表,一个是状态,另一个是设备类型。然后,我需要列出这些特定类型的设备修复的时间。每个设备可以有多个,所以我想要这样的东西:

Equipment Type  |  Status | 0-7 days | 8-15 days | 16-30 days | ...
Type A          |    B    |     3    |     2     |     0      | ...
Type B          |    B    |     1    |     0     |     13     | ...

等。以下是我尝试这样做的代码:

SELECT  EQP_STAT_EQP, EQP_TYP_EQP,
count(case [Days_Outstanding] when 'Less than 7 Days Outstanding     ' then 1 else null end) as [0_to_7_Days_Outstanding],
count(case [Days_Outstanding] when '8 to 14 Days Outstanding         ' then 1 else null end) as [8_to_14_Days_Outstanding],
count(case [Days_Outstanding] when '15 to 30 Days Outstanding        ' then 1 else null end) as [15_to_30_Days_Outstanding],
count(case [Days_Outstanding] when '31 to 60 Days Outstanding        ' then 1 else null end) as [31_to_60_Days_Outstanding],
count(case [Days_Outstanding] when '61 to 90 Days Outstanding        ' then 1 else null end) as [61_to_90_Days_Outstanding],
count(case [Days_Outstanding] when '91 to 120 Days Outstanding       ' then 1 else null end) as [91_to_120_Days_Outstanding],
count(case [Days_Outstanding] when 'Greater than 120 Days Outstanding' then 1 else null end) as [120_Plus_Days_Outstanding]
INTO Repair_Status_Summary
FROM Total_Equipment 
WHERE EQP_STAT_EQP='B'
GROUP BY EQP_STAT_EQP, EQP_TYP_EQP

然而,这一直给我错误:

'Msg 245, Level 16, State 1, Line 143
Conversion failed when converting the varchar value ''Less than 7 Days Outstanding     '' to data type int.'

之前我已经完成了这种类型的表,就像这样,甚至复制并粘贴它并更改了可能解决问题的字段名称无效,唯一的区别是我添加的WHERE语句

我不明白的是为什么它说它是varchar,当我将Days_Outstanding定义为char(35)时。所以我甚至放弃了Total_Equipment表并再次重新填充它。所以,如果您有任何想法,我们表示赞赏。

修改

@Mark Ba​​nnister - 谢谢!我现在感到很愚蠢,但我只是没有看到它。我应该有一个字段[Aging_Bucket],我使用[Days_Outstanding]来定义。很抱歉每个人浪费时间,我只是没有看到它。

1 个答案:

答案 0 :(得分:3)

then 1

需要

then '1'

1是整数,'1'是varchar

SELECT  EQP_STAT_EQP, EQP_TYP_EQP,
count(case [Days_Outstanding] when 'Less than 7 Days Outstanding     ' then '1' else null end) as [0_to_7_Days_Outstanding],
count(case [Days_Outstanding] when '8 to 14 Days Outstanding         ' then '1' else null end) as [8_to_14_Days_Outstanding],
count(case [Days_Outstanding] when '15 to 30 Days Outstanding        ' then '1' else null end) as [15_to_30_Days_Outstanding],
count(case [Days_Outstanding] when '31 to 60 Days Outstanding        ' then '1' else null end) as [31_to_60_Days_Outstanding],
count(case [Days_Outstanding] when '61 to 90 Days Outstanding        ' then '1' else null end) as [61_to_90_Days_Outstanding],
count(case [Days_Outstanding] when '91 to 120 Days Outstanding       ' then '1' else null end) as [91_to_120_Days_Outstanding],
count(case [Days_Outstanding] when 'Greater than 120 Days Outstanding' then '1' else null end) as [120_Plus_Days_Outstanding]
INTO Repair_Status_Summary
FROM Total_Equipment 
WHERE EQP_STAT_EQP='B'
GROUP BY EQP_STAT_EQP, EQP_TYP_EQP