如何获得最大和最小日期之间的平均差异?

时间:2012-10-16 06:06:02

标签: sql sql-server sql-server-2008 tsql

我正试图获得两个日期之间平均月数差异:

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.

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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