0

我正在尝试获取两个日期之间的平均月数差异:

select client_id, 
        avg(12*(year(MAX(received_date))-year(min(received_date))) 
        + MONTH(MAX(received_date))-MONTH(min(received_date)))
        from tmpTwoAccessions
        group by CLIENT_ID,PATIENT_ID

我收到这条消息:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

你能告诉我我在这里做错了什么吗?非常感谢您的指导。

4

3 回答 3

3

尝试使用这样的子查询:

select
    T.client_id
    ,avg(T.ReceivedDateDiff)
from 
(
    select client_id, 
    (12*(year(MAX(received_date))-year(min(received_date))) 
        + MONTH(MAX(received_date))-MONTH(min(received_date))) AS ReceivedDateDiff
    from tmpTwoAccessions
    group by CLIENT_ID,PATIENT_ID
)
T
GROUP BY client_id
于 2012-10-16T06:13:44.703 回答
2

您在子查询中计算 MAX 和 MIN 之间的差异,然后在外部查询中对其进行平均。

SELECT client_id, AVG(delta_date)
  FROM (SELECT client_id, patient_id,
               12 * (YEAR(MAX(received_date))-YEAR(MIN(received_date))) 
               + MONTH(MAX(received_date)) - MONTH(MIN(received_date))) AS delta_date
          FROM tmpTwoAccessions
         GROUP BY client_id, patient_id
       ) AS x
 GROUP BY client_id;

我不相信您的日期差异表达式是最佳的,但我没有尝试更改它。


Yurly Rozhovetskiy建议表达:

DATEDIFF(MONTH, MIN(received_date), MAX(received_date))

这对我来说看起来不错。修改后的查询变为:

SELECT client_id, AVG(delta_date)
  FROM (SELECT client_id, patient_id,
               DATEDIFF(MONTH, MIN(received_date), MAX(received_date)) AS delta_date
          FROM tmpTwoAccessions
         GROUP BY client_id, patient_id
       ) AS x
 GROUP BY client_id;
于 2012-10-16T06:13:58.127 回答
2

使用 DATEDIFF 实现会更干净。

WITH tmpTwoAccessionsMonths AS(         
    select 
          client_id
        , PATIENT_ID
        , DATEDIFF(month,MIN(received_date),MAX(received_date)) MonthDifference
    from 
        tmpTwoAccessions
    group by 
        CLIENT_ID,PATIENT_ID
)
SELECT
    client_id
    ,AVG(MonthDifference)
FROM
    tmpTwoAccessionsMonths
GROUP BY
    client_id
于 2012-10-16T13:50:40.193 回答