我试图通过目的地获取订单请求的交货日期和实际交货日期之间的平均差异。以下是给我的问题。你知道我哪里错了吗?我得到的消息是“每个GROUP BY表达式必须至少包含非外部引用的列”
SELECT CONCAT(Locations.City, ', ', Locations.State) AS Destination,
AVG(DATEDIFF("Day", Orders.ReqDate, Orders.SchedDate)) AS "Average Diff"
FROM dbo.Orders,
dbo.Locations
WHERE dbo.Orders.OrderNum= dbo.Locations.OrderNum
GROUP BY 'Destination'
答案 0 :(得分:2)
有几种方法可以改善您的查询。我建议:
SELECT CONCAT(l.City, ', ', l.State) AS Destination,
AVG(DATEDIFF(Day, o.ReqDate, o.SchedDate)*1.0) AS "Average Diff"
FROM dbo.Orders o join
dbo.Locations l
ON o.OrderNum = l.OrderNum
GROUP BY CONCAT(l.City, ', ', l.State) ;
请注意以下事项:
"Day"
- > Day
。 Day
是SQL Server中的关键字,不需要引号。o
和l
来提高查询的可读性。1.0
。 DATEDIFF()
返回一个整数。整数的平均值(在SQL Server中)是一个整数。通常,您需要一个十进制数字。您也可以将其转换为float
或其他格式,但我发现*1.0
是最快速转换的最简单方式。GROUP BY
(如其他答案中所述)。答案 1 :(得分:1)
尝试
SELECT CONCAT(Locations.City, ', ', Locations.State) AS Destination,
AVG(DATEDIFF("Day", Orders.ReqDate, Orders.SchedDate)) AS "Average Diff"
FROM dbo.Orders,
dbo.Locations
WHERE dbo.Orders.OrderNum= dbo.Locations.OrderNum
GROUP BY CONCAT(Locations.City, ', ', Locations.State)
答案 2 :(得分:1)
您正尝试使用字符串值'Destination'
进行分组,尝试将其更改为使用表达式CONCAT(Locations.City, ', ', Locations.State)
,它应该有效:
SELECT CONCAT(Locations.City, ', ', Locations.State) AS Destination,
AVG(DATEDIFF("Day", Orders.ReqDate, Orders.SchedDate)) AS "Average Diff"
FROM dbo.Orders,
dbo.Locations
WHERE dbo.Orders.OrderNum= dbo.Locations.OrderNum
GROUP BY CONCAT(Locations.City, ', ', Locations.State)