来自带有HAVING子句的SQL Query的COUNT结果

时间:2010-09-22 14:11:10

标签: sql sql-server count greatest-n-per-group

您是否可以在具有HAVING子句的查询中使用COUNT,以便COUNT返回行数?当我尝试时,我得到ID显示在表格中的次数。这是查询:

SELECT col_appid, min(col_payment_issued_date) as PayDate  
FROM tbl_ui_paymentstubs  
WHERE isnull(col_payment_amount,0) > 0  
GROUP BY col_appid  
HAVING min(col_payment_issued_date) >= '09/01/2010' and min(col_payment_issued_date) <= '09/30/2010'

我回来了6行,这很好,但我想回到6号。

我发现我可以这样做,但想知道是否还有另一种更优雅的方式:

WITH Claims_CTE(AppID, PayDate) as
(  
 SELECT col_appid, min(col_payment_issued_date) as PayDate
 FROM tbl_ui_paymentstubs
 WHERE isnull(col_payment_amount,0) > 0
 GROUP BY col_appid
 HAVING min(col_payment_issued_date) >= '09/01/2010' and min(col_payment_issued_date) <= '09/30/2010'
)  
 SELECT count(AppID) as Amount from Claims_CTE

`

4 个答案:

答案 0 :(得分:11)

COUNTGROUP BY子句一起使用将为每个组提供计数。如果您想要计算组数,则必须是单独的查询(如CTE示例)。

我只使用一个简单的子查询,而不是CTE:

SELECT COUNT(*) FROM 
 (SELECT col_appid, min(col_payment_issued_date) as PayDate  
  FROM tbl_ui_paymentstubs  
  WHERE isnull(col_payment_amount,0) > 0  
  GROUP BY col_appid  
  HAVING
     min(col_payment_issued_date) >= '09/01/2010'
     and min(col_payment_issued_date) <= '09/30/2010') Claims

答案 1 :(得分:4)

您也可以使用子查询。

SELECT count(*) as Amount
FROM (
    SELECT col_appid FROM tbl_ui_paymentstubs
    WHERE isnull(col_payment_amount,0) > 0
    GROUP BY col_appid
    HAVING min(col_payment_issued_date) BETWEEN '09/01/2010' AND '09/30/2010'
) Claims

答案 2 :(得分:2)

假设你有一个表格,其中包含一个名为App的col_appid值的独特列表,这个查询也可以运行,也可能是更好的表现:

SELECT Count(*)
FROM
   App A
   CROSS APPLY (
      SELECT TOP 1 col_payment_issued_date
      FROM tbl_ui_paymentstubs P
      WHERE
         P.col_payment_amount > 0
         AND A.col_appid = P.col_appid
      ORDER BY col_payment_issued_date
   ) X
WHERE
   X.col_payment_issued_date >= '09/01/2010'
   AND X.col_payment_issued_date < '10/01/2010'

如果没有App表,您可以替换(SELECT DISTINCT col_appid FROM tbl_ui_paymentstubs) A,但这样做也不会。与其他查询相比,它仍然可能是一个竞争者。

其他说明:

  • 您不需要执行isnull(column, 0) > 0因为column > 0已经排除了NULL。

  • @ ar和@bdukes的查询在内部SELECT子句中不需要任何内容​​,它们可以只是SELECT 1,这可能是性能改进(没有其他任何改变)

  • 我希望col_payment_issued_date存在约束,以便值没有时间部分,例如11:23 AM,否则BETWEEN子句最终将无法提取整个月的正确数据。

    < / LI>

<强>更新

  • 对于它的价值,日期格式'20100901'将随处可用,使用任何语言或DATEFIRST设置。我鼓励你养成使用它的习惯。其他格式如'09 / 01/2010'或'2010/09/01'等可能会让月份和日期混乱。
@DScott说:

  

有一个tbl_Application,但在这个例子中没有使用。我可以加入它,但我只计算此查询的付款,因此不需要。

与其他方法相比,您是否介意尝试我的查询并向我提供有关其性能的反馈?我希望即使在查询中有额外的连接,它也表现得很好。

答案 3 :(得分:0)

使用下面的查询对Oracle中的重复记录进行计数。

SELECT Column1 , count(*) Num
FROM TABLE_NAME whe   
GROUP BY Column1 
HAVING count(*) > 1  
ORDER BY num desc;