2016-06-30 18 views
0

我被连接的表上的COUNT上的SELECT查询卡住了。我正在开发Visual Studio 2015,使用VB.net和SQL Server Express x86(SQL Server 12.0.2269)的asp.net。连接表中的SQL计数在GROUP BY上给出了错误

这是表:

Products 

- Id (PK, int, not null) 
- Number (varchar(20), not null) 
- CategoryId (int, not null) 
- Name (varchar(50), not null) 
- Description (text, not null) 
- IsActive (bit, not null) 
- Stock (int, not null) 
- SetColors (bit, not null) 
- SetSizes (bit, not null) 
- MakeId (FK, int, null) 
- StockTypeId (FK, int, not null) 

Groups 

- Id (PK, FK, int, not null) 
- Name (varchar(50), not null) 
- Description (text, null) 
- Picture (image, null) 

ProductGroups 

- Id (PK, int, not null) 
- ProductId (FK, int, not null) 
- GroupId (FK, int, not null) 

每一个产品可以属于一个或多个组,什么是在ProductGroups表中。

我需要一个查询来选择Groups.Id,Groups.Name,Groups.Picture和属于每个组的产品的计数,以显示在数据绑定asp:ListView中。

无论我尝试什么,我在名称和图片列上都会遇到错误,因为它们是“未包含在聚合函数或GROUP BY子句中”。

我一直在寻找解决方案。这是最后的查询我想:

SELECT g.Id, g.Name, g.Picture, COUNT(DISTINCT pg.ProductId) as numProd 
FROM Groups g 
LEFT JOIN ProductGroups pg ON g.Id = pg.GroupId 
GROUP BY g.Id, g.Name, g.Picture, pg.ProductId 

我不知道什么聚合函数,我应该在VARCHAR或为空的图像场使用,并在图像分组不允许任何“文本,ntext和图像数据类型不能被比较或排序,除非使用IS NULL或LIKE运算符“)。

任何人都可以帮助我解决这个问题吗?

在第二步中,我还需要过滤StockTypeId,MakeId,CategoryId,isActive和Stock。但是当第一步工作时,这很容易。

回答

1

SELECT g.Id, g.Name, g.Picture, pg.pg_count 
FROM Groups g 
JOIN (Select GroupId, Count(*) as pg_count 
    FROM ProductGroups Group By GroupId) pg on g.Id = pg.GroupId 
+0

非常感谢!这是诀窍。今天我学到了一些东西! –

+0

是的,无论何时您发现自己按名称或说明字段进行分组,您可能是在做错某事。 –

0

这应该工作,除非有一个与你的表关系的问题:我觉得这个查询会做的伎俩

SELECT g.Id, g.Name, g.Picture, COUNT(DISTINCT pg.ProductId) asnumProd FROM Groups g LEFT JOIN ProductGroups pg ON g.Id = pg.GroupId GROUP BY g.Id, g.Name, g.Picture

+0

谢谢您的回答。当我运行这个查询时,我再次遇到错误_Msg 306,Level 16,State 2,Line 3:文本,ntext和图像数据类型无法进行比较或排序,除非使用IS NULL或LIKE运算符._也许可以使用 我应该检查我的关系,它们是由实体框架创建的。 –

+0

oh g.Picture is throwing you off –

+0

你需要图片数据吗? –