如果某个国家/地区的小部件属于多个类别,我正在尝试按分组获取计数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
答案 0 :(得分:0)
从GROUP BY中删除wc.WidgetImpressionID
。这是添加额外级别的分组,恰好是所需结果的计数
将COUNT
更改为COUNT(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