我无法运行以下查询。
我需要在每周的每一天找到每个模型使用的许多[ID]。我在运行类似查询以总结其他指标时没有遇到任何问题。
但在这种情况下,我收到一条消息“将varchar值'07:2767:90:56'转换为数据类型int时转换失败”。
我可以在没有(if 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;
答案 0 :(得分: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;
答案 1 :(得分:0)
我不确定你为什么会遇到这个特定错误,但我看到了几个问题:
您的查询不会返回您要查找的结果。这几天所有的计数都是一样的。您希望使用SUM,类似于:
SUM(例如,当datepart(工作日,[日期])= 2那么其他0结束)AS [星期一]