0

如果一个国家/地区的小部件的类别中有多个,我正在尝试分组以获取计数 1。

为了更好地解释它,这是我到目前为止得到的代码:

select c.Name As Country, w.Description As WidgetName, cat.Description As Category,
  COUNT (wc.Id)AS Clicks  
  from ManufacturerWidgets mw
 join WidgetClicks wc on mw.Id = wc.ManufacturerWidgetId
 join Products p on   wc.ProductId = p.Id
 join Countries c on mw.CountryId = c.Id
 join Widgets w on w.Id = mw.WidgetId
 join Categories cat on cat.Id = p.CategoryId
 where mw.Enabled = 1 and  mw.ManufacturerId = 17 and wc.CreatedAt >= '2013-01-01 00:00:00.000' and wc.CreatedAt <= '2013-07-05 23:59:00.000'
 GRoup By wc.WidgetImpressionId, c.Name,  w.Description,  cat.Description
 HAVING wc.WidgetImpressionId > 0
 order by  c.Name, w.Description, cat.Description

例如,这将返回:

County   WidgetName   Category    Clicks

Austria  onebysix     computing   1
Austria  onebysix     computing   4
Austria  onebysix     printing    1
Austria  onebysix     printing    3
Austria  onebysix     printing    2

我需要返回的是每个类别的交互,所以:

Austria  onebysix     computing   4  - this would be 1 not 4

我需要按类别对它们进行分组,因此最终结果将是:

Austria  onebysix     computing   2
Austria  onebysix     printing    3
4

1 回答 1

0

wc.WidgetImpressionID从 GROUP BY 中删除。这是添加额外级别的分组,这恰好是所需结果的计数

将 更改COUNTCOUNT(wc.WidgetImpressionID)分别给出 2 和 3

HAVING 应该是HAVING COUNT(wc.WidgetImpressionID) > 0. 在您的代码中,它的作用类似于 WHERE 子句过滤器,因为它位于 GROUP BY 中(请参阅上面的第一点)

select c.Name As Country, w.Description As WidgetName, cat.Description As Category,
  COUNT (wc.WidgetImpressionID) AS Clicks  
  from ManufacturerWidgets mw
 join WidgetClicks wc on mw.Id = wc.ManufacturerWidgetId
 join Products p on   wc.ProductId = p.Id
 join Countries c on mw.CountryId = c.Id
 join Widgets w on w.Id = mw.WidgetId
 join Categories cat on cat.Id = p.CategoryId
 where mw.Enabled = 1 and  mw.ManufacturerId = 17 and wc.CreatedAt >= '2013-01-01 00:00:00.000' and wc.CreatedAt <= '2013-07-05 23:59:00.000'
 GRoup By c.Name,  w.Description,  cat.Description
 HAVING COUNT(wc.WidgetImpressionID) > 0
 order by  c.Name, w.Description, cat.Description
于 2013-07-12T09:28:13.387 回答