0

我无法运行以下查询。

我需要在每周的每一天找到每个模型使用的 [ID] 数量。我运行类似的查询来总结其他指标没有问题。

但在这种情况下,我收到一条消息“将 varchar 值 '07:2767:90:56' 转换为数据类型 int 时转换失败”。

我可以在没有(case if)函数的情况下对 [ID] 执行计数查询,没有任何问题。

SELECT model,

 count(CASE WHEN datepart(weekday, [date]) =2 THEN (ID)else 0 END) AS [Monday]
 count(CASE WHEN datepart(weekday, [date]) =3 THEN (ID)else 0 END) AS [Tuesday]
 count(CASE WHEN datepart(weekday, [date]) =4 THEN (ID)else 0 END) AS [Wednesday]
 count(CASE WHEN datepart(weekday, [date]) =5 THEN (ID)else 0 END) AS [Thursday]
 count(CASE WHEN datepart(weekday, [date]) =6 THEN (ID)else 0 END) AS [Friday]

from clientdata 

where [date] between cast ((GETDATE() -7) AS date) and cast (GETDATE()-1 AS date)
group by d.model;
4

2 回答 2

1

尝试这个

SELECT model,

 count(CASE WHEN datepart(weekday,[date])=2 THEN ID else 0 END) AS [Monday],
 count(CASE WHEN datepart(weekday,[date])=3 THEN ID else 0 END) AS [Tuesday],
 count(CASE WHEN datepart(weekday,[date])=4 THEN ID else 0 END) AS [Wednesday],
 count(CASE WHEN datepart(weekday,[date])=5 THEN ID else 0 END) AS [Thursday],
 count(CASE WHEN datepart(weekday,[date])=6 THEN ID else 0 END) AS [Friday]

from clientdata  d

where [date] between (GETDATE() -7) and (GETDATE()-1)
group by d.model;
于 2012-07-31T17:34:59.017 回答
0

我不确定您为什么会收到该特定错误,但我发现了几个问题:

  • 您选择的字段后没有逗号(在星期一、星期二等之后需要一个逗号)
  • 您按 d.model 分组,其中 d 不是有效的表别名
  • 您的查询不会返回您正在寻找的结果。这些天的所有计数都将相同。您想使用 SUM,类似于:

    SUM(CASE WHEN datepart(weekday, [date]) =2 THEN 1 else 0 END) AS [Monday]

于 2012-07-31T17:37:19.607 回答