如何在db2中使用group by子句执行COUNT(*)?

时间:2011-03-09 14:43:03

标签: sql db2

我想知道此查询将返回多少行:

SELECT 
  MONTH(DHSTMP), SUM(DHDLDY), SUM(DHBUDS), YEAR(DHSTMP) 
FROM 
  DSHDAY 
WHERE 
  DHSTMP BETWEEN '2009-07-26 00:00:00' AND '2011-03-09 23:59:59' 
GROUP BY 
  YEAR(DHSTMP), MONTH(DHSTMP) ORDER BY YEAR(DHSTMP), MONTH(DHSTMP)

所以我试过了:

SELECT 
  COUNT(*) 
FROM 
  DSHDAY 
WHERE 
  DHSTMP BETWEEN '2009-07-26 00:00:00' AND '2011-03-09 23:59:59' 
GROUP BY 
  YEAR(DHSTMP), MONTH(DHSTMP)

但它告诉我每组有多少行。

如何获取第一个查询将返回的行数?

1 个答案:

答案 0 :(得分:7)

这应该有效。但它不是高效的。
(如果你只对计数感兴趣,你可能不想计算总和和排序)

SELECT COUNT(*)
FROM (
  SELECT 
    MONTH(DHSTMP), 
    SUM(DHDLDY), 
    SUM(DHBUDS), 
    YEAR(DHSTMP) 
  FROM DSHDAY 
  WHERE DHSTMP BETWEEN '2009-07-26 00:00:00' AND '2011-03-09 23:59:59' 
  GROUP BY 
    YEAR(DHSTMP), 
    MONTH(DHSTMP) 
  ORDER BY 
    YEAR(DHSTMP), 
    MONTH(DHSTMP)
) i


试试这个

SELECT COUNT( DISTINCT i.month_year )
FROM (
  SELECT 
    CONCAT( MONTH(DHSTMP), YEAR(DHSTMP) ) AS month_year
  FROM DSHDAY 
  WHERE DHSTMP BETWEEN '2009-07-26 00:00:00' AND '2011-03-09 23:59:59' 
) i


变化(回答迈克的评论)

SELECT COUNT(*)
FROM (
  SELECT 0
  FROM DSHDAY 
  WHERE DHSTMP BETWEEN '2009-07-26 00:00:00' AND '2011-03-09 23:59:59' 
  GROUP BY 
    YEAR(DHSTMP), 
    MONTH(DHSTMP) 
) i