[英]SQL Query that returns only records with multiple rows
我有一个包含两个表的数据库: Customers
和Services
。
Customer
表具有帐户信息, Services
表具有我公司已执行的每项服务的单独记录。
Services
表通过ID
列链接到Customer
表,其中Customers.ID = Services.CustomerID
。
我正在尝试执行一个查询,该查询将仅返回在指定日期范围内已执行一项以上服务的那些客户的客户名和帐号。 例如,向我显示所有客户在2015年执行过两次以上工作的客户。
如何编写此类查询,以便仅返回具有多次服务访问的查询? 我可以使用游标,计数结果等来执行此操作,但似乎必须有一种更有效的方法。
像这样使用JOIN
和GROUP BY
:
SELECT Customers.ID
FROM Customers
JOIN Services ON Customer.ID=Services.CustomerID
--WHERE your Services date check here
GROUP BY Customers.ID -- you can add more columns from the customers table here and in the select as needed
HAVING SUM(1)>1
您可以添加WHERE
子句以过滤Services
的日期范围(就在GROUP BY
之前)。
从计数的客户C中选择ID(从C中的C.id = S.CustomersId的服务S中选择*)> 1
SELECT Customers.CustomerID
,Customers.Name
,Customers.AcoountNumber
FROM Customers
JOIN
(
select Services.CustomerID, Services.CustomerID as totalServices
from Services
where Services.date BETWEEN @FROM_DATE AND @TO_DATE
group by Services.CustomerID
having count(Services.CustomerID) >1
) AS CustomersMoreThan1 on Customers.CustomerID=CustomersMoreThan1.CustomerID
此查询使您可以从客户表中添加更多列,而无需修改GROUP BY。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.