1

我们有这四个表:

Store (
    row bigint,
    id uniqueidentifier,
    name varchar
)

Products (
    row bigint,
    id uniqueidentifier,
    storeID uniqueidentifier,
    productname varchar
)

Customer (
    row bigint,
    id uniqueidentifier,
    storeID uniqueidentifier,
    fName,
    lName,
    email
)

orders (
    row bigint,
    id uniqueidentifier,
    store_ID uniqueidentifier,
    cust_id uniqueidentifier,
    prod_id uniqueidentifier,
    date datetime
)

我们正在设计一个查询,它将查找从特定商店有 110 到 250 个订单的所有客户?

我们正在尝试列出客户名称、商店名称以及来自特定商店的该客户的订单数量。

我们尝试过的查询是:

select c.firstname + ' '+c.LastName, c.EmailAddress, s.name,  COUNT(o.id) from Orders o 
    inner join store s on s.ID=o.store_ID 
            inner join Customers c on c.ID=o.cust_ID 
    group by (c.firstname + ' '+c.LastName+cast(o.cust_ID as varchar(max) ))
    having count(o.id) >110 and count(o.id)<250

但是我们从上面的 join 语句中得到了错误。知道我们做错了什么吗?

4

2 回答 2

1

尝试通过以下方式简单地列出组中的非聚合列:

select
    c.firstname + ' ' + c.LastName,
    c.EmailAddress,
    s.name,
    count(o.id)
from Orders o
inner join store s on s.ID=o.store_ID
inner join Customers c on c.ID=o.cust_ID
group by c.firstname + ' ' + c.LastName,
    c.EmailAddress,
    s.name
having count(o.id) between 111 and 249

还要注意通过使用betweenforhaving条件进行的简化,尽管因为包含在内而对范围值进行了修改between

于 2013-08-29T00:27:32.443 回答
0

问题是您没有按 select 语句中的所有列进行分组:

select c.firstname + ' '+c.LastName, c.EmailAddress, s.name,  COUNT(o.id) from Orders o 
    inner join store s on s.ID=o.store_ID 
            inner join Customers c on c.ID=o.cust_ID 
    group by c.firstname + ' '+c.LastName, c.EmailAddress, s.name
    having count(o.id) >110 and count(o.id)<250
于 2013-08-29T00:28:38.733 回答