我们有这四个表:
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语句中得到错误。关于我们做错了什么的任何想法?
答案 0 :(得分: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
请注意使用between
进行having
条件的简化,虽然修改了范围值,因为between
是包容性的。
答案 1 :(得分: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