我被连接的表上的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。但是当第一步工作时,这很容易。
非常感谢!这是诀窍。今天我学到了一些东西! –
是的,无论何时您发现自己按名称或说明字段进行分组,您可能是在做错某事。 –