SQL 服务器 Select 计数 > 1

SQL Server Select count > than 1

项目:经典 ASP VBScript / SQL Server 2012

我有 2 个 table,ProductsCategories

我想构建一个 SQL 查询,它将 return 具有 多个 的类别] 产品。

2个table之间的公共键是列Category_id(存在于Products table和Categories table).

你试试这个:

SELECT * 
FROM Categories C
WHERE C.Category_id IN ( SELECT P.Category_id FROM Products P GROUP BY P.Category_id HAVING COUNT(*) > 1) 

您可以对此类查询使用 having 子句,该子句在 完成所有聚合后过滤您的数据集:

declare @Categories table(CategoryID int);
declare @Products table(ProdID int, CategoryID int);

insert into @Categories values(1),(2),(3);
insert into @Products values(10,1),(20,1),(30,2),(40,2),(50,3);

select c.CategoryID
        ,count(1) as ProductCount
from @Categories c
    left join @Products p
        on(c.CategoryID = p.CategoryID)
group by c.CategoryID
having count(1) > 1;

输出:

+------------+--------------+
| CategoryID | ProductCount |
+------------+--------------+
|          1 |            2 |
|          2 |            2 |
+------------+--------------+

将简单 Group byHaving 用作下一个演示:-

create table Products (ProductID int, name varchar(50), Category_id int )
insert into Products 
values
(1,'aaaa',1),
(2,'bbbb',1),
(3,'ccccc',2),
(4,'11111',2),
(5,'11111ccc',3)

create table Categories (Category_id int, name varchar(50))
insert into Categories 
values
(1,'Letters'),
(2,'Numbers'),
(3,'NumbersAndLetters')

-- CategoryID = 3 has only one product ..

select p.Category_id ,count(p.ProductID) CountProducts from 
Products p inner join Categories c
on p.Category_id = c.Category_id
group by p.Category_id
having count(p.ProductID) > 1

结果:-

Category_id CountProducts
   1              2
   2              2