sql查询以下内容

时间:2015-09-12 17:46:45

标签: sql sql-server

  1. PERSON - 电子邮件ID,电话号码,地址,姓名,年龄,性别
  2. 订购 - 订单,配方,配料,电子邮件ID,订单ID,订单状态
  3. ADDRESS - 地址,商店位置,手机号
  4. 假设这些是数据库中的三个表和各自的列。

    获取每家商店销售额最高的食谱的查询是什么?

    我使用了这个查询,但它显示了一半的结果。

    select distinct Store_Location, Recipe, No_of_Orders 
    from [ORDER] 
    join PERSON on [ORDER].Email_ID = PERSON.Email_ID 
    join ADDRESS on PERSON.Address = ADDRESS.Address
    

1 个答案:

答案 0 :(得分:2)

像这样:

Bool

此查询的工作原理是将原始查询的行与返回当前行存储的最大select distinct Store_Location, Recipe, No_of_Orders from [ORDER] As o join PERSON As p on o.Email_ID = p.Email_ID join ADDRESS As a on p.Address = a.Address WHERE No_of_Orders = ( select MAX(o2.No_of_Orders) from [ORDER] As o2 join PERSON As p2 on o2.Email_ID = p2.Email_ID join ADDRESS As a2 on p2.Address = a2.Address Where a2.Address = a.Address ) 的子查询进行比较。如果它们匹配,那么这必须是" 该商店销售额最高的食谱",所以我们保留它,否则我们将它从最终的行集中排除

No_of_OrdersAs o位被称为"表别名"。它们是为查询中的表的每种不同用法提供本地名称的方法。它们在这里是必要的,因为在子查询中我们重新查询与外部查询中相同的表,我们需要能够区分我们所引用的每个列的含义。