统计所有唯一记录

时间:2013-05-23 14:41:38

标签: php mysql

我有一个具有以下格式的数据库:

myTable
productgroupID | productID | views | date
1              | 10        | 25    | 2013-05-23 
4              | 105       | 15    | 2013-05-23 
7              | 60        | 65    | 2013-05-23
7              | 60        | 55    | 2013-05-22
7              | 60        | 45    | 2013-05-21 

现在我想总结一下产品的所有观点。 结果应该是:

productgroupID | productID | viewed | month
7              | 60        | 165    | 2013-05-01
1              | 10        | 25     | 2013-05-01 
4              | 105       | 15     | 2013-05-01 

我尝试了下面的查询,但这给了我一个特定productgroupID的所有视图。但我需要唯一的productgroupID&的总和。的productID。

SELECT COUNT( views ) AS viewed, productgroupID FROM product_stats_daily GROUP BY productgroupID

3 个答案:

答案 0 :(得分:2)

如果您希望汇总观看次数,则可以使用sum()汇总功能,然后您可以按monthyear分组日期:

select productGroupId,
  productId,
  sum(views) viewed,
  month(date) Month,
  year(date) Year
from myTable
group by productGroupId, productId, month(date), year(date);

请参阅SQL Fiddle with Demo

您还可以使用Date_Format以您想要的格式获取日期:

select productGroupId,
  productId,
  sum(views) viewed,
  DATE_FORMAT(date, '%Y-%m-01') date
from myTable
group by productGroupId, productId, DATE_FORMAT(date, '%Y-%m-01')

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

COUNT将计算行数,而SUM将计算检索到的行的值。

所以你的查询变为:

SELECT SUM( views ) AS viewed, productgroupID
FROM product_stats_daily
GROUP BY productgroupID

答案 2 :(得分:1)

可能有更优雅的方式将日期强制到月初,但这应该有效:

SELECT
  ProductGroupID,
  ProductID,
  SUM(views) AS viewed,
  DATE_FORMAT(date, '%Y-%m-01') AS Month
FROM myTable
GROUP BY
  ProductGroupID,
  ProductID,
  DATE_FORMAT(date, '%Y-%m-01')