SQL查询结果集,我需要按DAY分组的SUM(数量)COLUMN

时间:2013-07-10 14:04:05

标签: sql count sum having

这是我在product表格LEFT JOIN pageON上使用的查询productid pageidproduct中的SELECT COUNT(DISTINCT `p`.`id`) as `quantity`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day` FROM `product` AS `p` LEFT JOIN `page` AS `pg` ON `p`.`id` = `pg`.`productid` WHERE `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59' AND `p`.`group` = '101' GROUP BY `day`, `p`.`id` HAVING COUNT(`pg`.`productid`)>=10 ORDER BY `p`.`created_time` 非常简单。

**product**
id  created_time
32  2013-07-09
33  2013-07-09

**page**
id  productid
1   33
2   33
..  ..
20  33
21  32
22  32
..  ..
54  32

有关的两个示例表:

quantity    day
1           2013-07-09
1           2013-07-09
1           2013-07-10

现在我的结果集如下所示:

UNION

但我希望以下输出没有temp且不使用quantity day 2 2013-07-09 1 2013-07-10 表:

product

现在我的代码示例中添加了两个表。我需要page的数量为day,其中{{1}}按{{1}}分组{/ 1}

3 个答案:

答案 0 :(得分:1)

我认为这是因为你要在p.id条款中留下group by。试试这个:

SELECT COUNT(DISTINCT `p`.`id`) as `quantity`,
       DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM `product` AS `p` LEFT JOIN
     `page` AS `pg`
      ON `p`.`id` = `pg`.`productid` 
WHERE `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
      AND `p`.`group` = '101' 
GROUP BY `day`
HAVING COUNT(`pg`.`productid`)>=10 
ORDER BY `p`.`created_time`

答案 1 :(得分:1)

不要GROUP BY id值,ORDER BY也可以day

请注意,day在标准SQL中的GROUP BYsql_mode is using "only_full_group_by"时不可用。 MySQL允许它作为扩展,但它具有误导性

SELECT 
    COUNT(*) as `quantity`,
    DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM
   `product` AS `p` 
   JOIN
   `page` AS `pg` ON `p`.`id` = `pg`.`productid` 
WHERE
   `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
   AND
   `p`.`group` = '101' 
GROUP BY
   `pg`.`productid`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
HAVING
   COUNT(*) >= 10 
ORDER BY
   `day`;

答案 2 :(得分:1)

我找到了查询的解决方案:

SELECT
COUNT(`p`.`id`) as `quantity`,
DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM
`product` AS `p`
INNER JOIN 
(
SELECT 
    `productid` AS `id`,
    count(id) AS pagesNR 
FROM 
    `page`
GROUP BY 
    `productid` HAVING COUNT(`id`) >= 10
)
AS 
`pg` USING (`id`)
WHERE
    `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
AND
    `p`.`group` = '101'
GROUP BY 
    `day`
ORDER BY 
    `created_time`

感谢我的同事DaniëlVersteeg的朋友