计算结果集中的实例

Count Instances in Result Set

我正在查询以监控给定时间范围内紧急医疗服务的使用情况,在本例中为一年的四分之一。当我尝试执行计算 VisitCount 的子查询时,它提取为该客户记录的每项索赔,在某些情况下高达 4000。我只想要过去 91 天内紧急服务产生的索赔数量,通常不超过 10。

以下是查询的相关部分,我不确定是否已注释掉:

SELECT
    UMI,
    PIN,
    Agreement,
    --sq.VisitCount,
    med.Code,
    Date
    
FROM main
/*
    INNER JOIN (
    SELECT Agreement, COUNT(*) as VisitCount
    FROM main
    GROUP BY Agreement
    ) AS sq ON main.Agreement = sq.Agreement
*/
--Inner Joins that work are excluded
    
WHERE 
    med.Code BETWEEN '99281' AND '99285'
    AND Date >= (CURRENT_DATE - 91)
    --AND VisitCount >= 3
--GROUP BY Agreement
ORDER BY VisitCount DESC
    ;
SELECT Agreement, COUNT(*) as VisitCount
FROM main
GROUP BY Agreement

将获得 table 中每个 agreement 的所有计数(因为没有 WHERE 条件)。要按日期限制计数,您需要在子查询中使用该条件:

SELECT Agreement, COUNT(*) as VisitCount
FROM main
WHERE Date >= (CURRENT_DATE - 91)
GROUP BY Agreement

为了避免重复条件(在你的内部和外部查询中都有它),你可以使用 CTE(大多数现代 DBMS 都支持这个):

WITH mainbydate AS
(
 SELECT *
 FROM main
 WHERE Date >= (CURRENT_DATE - 91)
)
SELECT *
FROM mainbydate INNER JOIN (
  SELECT Agreement, COUNT(*) as VisitCount
  FROM mainbydate
  GROUP BY agreement
 ) sq ON mainbydate.agreement = sq.agreement
WHERE med.Code BETWEEN '99281' AND '99285'