我在下面有一个查询尝试更新数据库的记录。我无法运行它并显示错误:
Msg 147,Level 15,State 1,Line 12
中
聚合可能不会出现在WHERE子句中,除非它位于子查询
更改2018年1月报告故障超过6次的所有自行车的状态,并将自行车状态设置为" C"。
更新了我的SQL命令:
UPDATE Bike
SET Status = 'C'
SELECT b.Status
FROM Bike b
INNER JOIN Fault ft ON b.BikeID = ft.BikeID
INNER JOIN Feedback fb ON ft.FBID = fb.FBID
WHERE ((COUNT(fb.FBID) > 6)
AND (DATEPART(YEAR, fb.FbDateTIME) = 2018)
AND (DATENAME(MONTH, fb.FbDateTIME) = 'January'))
包含在HAVING子句或选择列表中,正在聚合的列是外部引用。
由于我是SQL的新手,我不确定如何使子查询等效于此,并且任何人都可以帮助我吗?任何指导将不胜感激。
答案 0 :(得分:2)
您不能在Aggregate
子句中使用Where
函数。您需要使用Having
子句来过滤组。试试这样的事情
UPDATE b
SET Status = 'C'
FROM Bike b
WHERE EXISTS (SELECT 1
FROM Fault ft
INNER JOIN Feedback fb
ON ft.FBID = fb.FBID
WHERE b.BikeID = ft.BikeID
AND fb.FbDateTIME >= '2018-01-01'
AND fb.FbDateTIME < '2018-02-01'
HAVING Count(fb.FBID) > 6)
注意:要过滤Jan 2018
条记录,我更喜欢使用此fb.FbDateTIME >= '2018-01-01' AND fb.FbDateTIME < '2018-02-01'
方法。在DATEPART
子句中使用Where
函数将使查询不可搜索
答案 1 :(得分:0)
将COUNT(1)移至
UPDATE B
SET Status = 'C'
FROM Bike b
INNER JOIN Fault ft ON b.BikeID = ft.BikeID
INNER JOIN Feedback fb ON ft.FBID = fb.FBID
WHERE (
AND (DATEPART(YEAR, fb.FbDateTIME) = 2018)
AND (DATENAME(MONTH, fb.FbDateTIME) = 'January'))
HAVING (COUNT(fb.FBID) > 6)
答案 2 :(得分:0)
首先,UPDATE
SET Status= 'C'
语句无效后,SELECT
语句的语法不正确,WHERE
中的聚合函数不被允许,因此,经过这些更正后,可以使用子查询来实现所需的输出,如下所示:
UPDATE Bike SET Status= 'C'
FROM Bike b
INNER JOIN (
SELECT b.BikeID
FROM Bike b
INNER JOIN Fault ft ON b.BikeID=ft.BikeID
INNER JOIN Feedback fb ON ft.FBID=fb.FBID
WHERE (DATEPART(YEAR,fb.FbDateTIME)= 2018)
AND (DATENAME(MONTH,fb.FbDateTIME)= 'January')
GROUP BY BikeID HAVING (COUNT(fb.FBID)>6)) c ON c.bikeID = b.bikeID