Sql 列出购买订单的客户>;平均支付订单
以下是我的疑问:Sql 列出购买订单的客户>;平均支付订单,sql,sql-server-2008,Sql,Sql Server 2008,以下是我的疑问: select c.cust_lname, c.cust_fname, o.amount from CUSTOMER c, orders o where o.amount > (select AVG (o.amount) from orders o group by order_num having o.amount > AVG(o.amount)); 为什么不起作用?你设计得太过火了。从子查询中取出having子句。按照编写查询的方式,它看起来像: select
select c.cust_lname, c.cust_fname, o.amount
from CUSTOMER c, orders o
where o.amount >
(select AVG (o.amount)
from orders o
group by order_num
having o.amount > AVG(o.amount));
为什么不起作用?你设计得太过火了。从子查询中取出having子句。按照编写查询的方式,它看起来像:
select c.cust_lname, c.cust_fname, o.amount
from CUSTOMER c, orders o
where o.amount >
(select AVG (amount) from orders );
select c.cust_lname, c.cust_fname, o.amount
from CUSTOMER c join
orders o
on c.customerId = o.customerId
where o.amount > (select AVG (o.amount)
from orders o)
请注意,您需要将两个表连接在一起以获得所需的内容。@JeffOrris您还需要从子查询中删除
group by
(假设您需要所有订单的平均值)这些帮助,但是用户仍然会获得太多行,因为他们使用的是老式的“帮助我提高获得笛卡尔积的几率联接语法。获取错误:消息102,级别15,状态1,第4行“c”附近的语法不正确。@JeffOrris。您需要通过正确的字段连接表。将CustomerId
替换为连接这两个表的正确字段。错误消息是由于另一个未经测试的粗心答案。关键词Gordon上的在哪里?@GordonLinoff那么现在你要向Jeff道歉,让他看起来像是犯错的人吗?@GordonLinoff与其说是联合起来,不如说1)注意到你有一种倾向,2)看着这种倾向逐渐消失是一种乐趣。从技术上讲,你的答案在编辑之前也是完全错误的。顺便说一句,我没有投反对票,我计划在你的答案中的假设被OP验证后再投反对票。@JeffOrris根据你的问题,这似乎是正确的。想详细解释一下为什么结果太多吗?只有13个订单,我得到了45个结果。事实上,你需要加入客户和订单表格,比如来自客户c的加入订单o on c.orderId=o.Id
那么,“不工作”到底是什么意思?我的错,不工作意味着没有得到正确的输出。我想我应该说得更具体些