1

我正在尝试了解聚合函数如何在 SQL 中工作,但我无法计算出如何计算一个值在查询中出现的次数。

我使用MSSQL 2008,我尝试的一切似乎都会导致错误。

以下是我的查询:

SELECT category, 
       template, 
       galleryshortDescription, 
       galleryLongDescription, 
       GalleryName,   
       GalleryTitle, 
       GalleryID, 
       GalleryCreatedDate, 
       GalleryLastUpdated, 
       GalleryPublished, 
       GalleryViews, 
       ObjectID, 
       GalleryDescription, 
       HtmlMetaKeywords, 
       HtmlMetaDescription

FROM dbo.ImageGallery

我想返回该category字段以及它在此查询中出现的总次数,我尝试使用

count (category) AS category_counter

任何建议都非常感谢

提前致谢

4

4 回答 4

1

我想返回类别字段以及它在此查询中出现的总次数

您需要的是使用GROUP BY,COUNT像这样:

SELECT
  Category,
  COUNT(category) AS category_counter
FROM  dbo.ImageGallery
GROUP BY category;

SQL 小提琴演示

例如,这个查询会给你类似的东西:

|  CATEGORY | CATEGORY_COUNTER |
--------------------------------
| Category1 |                2 |
| Category2 |                2 |
| Category3 |                3 |
| Category4 |                3 |

但是你有一个大问题,在你的桌子上。

您的表格以这种方式未标准化,您应该将此表格拆分为以下表格:

Categories:

  • CategoryId,
  • CategoryName.

GalleriesProperties

  • GalleryId,
  • GalleryName,
  • GalleryshortDescription,
  • GalleryLongDescription,
  • GalleryTitle,
  • GalleryCreatedDate,
  • GalleryLastUpdated,
  • GalleryPublished,
  • GalleryViews,
  • GalleryDescription.

HTMLMetas

  • HTMLMetaID
  • HtmlMetaKeywords,
  • HtmlMetaDescription

那么你的桌子ImageGallery会是这样的:

  • GalleryId,
  • CategoryId一个外键引用类别表(CategoryID),
  • Template,
  • HTMLMetaIDhtmlmeta 表的外键。

这只是一个示例,它可能需要在您的上下文中进行更多调整。但是您应该阅读更多有关此内容的信息。

于 2012-12-19T09:53:28.513 回答
0

您必须使用 GROUP BY 和 COUNT。让我们尝试阅读:http ://www.w3schools.com/sql/sql_func_count.asp和http://www.w3schools.com/sql/sql_groupby.asp

于 2012-12-19T09:53:31.830 回答
0

您必须像这样使用 Count(category) 并按类别分组

SELECT  category, count(category) as ColumnNameofYourChoice
  FROM dbo.ImageGallery 
     group by category

使用计数时,您必须使用分组依据,您希望计数发生。

于 2012-12-19T09:58:55.147 回答
0

最好将类别和 No_of_category 存储在 Temp 表中。之后,您可以将您的表加入到临时表中。例如。

SELECT  category, count(category) No_Of_category
into #temp
  FROM dbo.ImageGallery 
     group by category

SELECT cat.category, t.No_Of_category,
      cat. template, 
       cat.galleryshortDescription, 
       cat.galleryLongDescription, 
       cat.GalleryName,   
       cat.GalleryTitle, 
       cat.GalleryID, 
       cat.GalleryCreatedDate, 
       cat.GalleryLastUpdated, 
       cat.GalleryPublished, 
       cat.GalleryViews, 
       cat.ObjectID, 
       cat.GalleryDescription, 
       cat.HtmlMetaKeywords, 
       cat.HtmlMetaDescription

FROM dbo.ImageGallery cat
left outer join #temp t on cat.category=t.category
于 2016-06-17T14:57:27.003 回答