我正在尝试计算此查询中每个授权号的总天数,但是我收到一条错误,指出聚合函数无法对具有聚合的表达式执行。我该如何解决这个问题?有几个授权号码,希望最短和最长日期能够在几天内提供准确的结果。
SELECT
CASE
WHEN DBO.FN_AGE(CL_DOB, AH_ADMDT) >= 18 THEN 'ADULT'
WHEN DBO.FN_AGE(CL_DOB, AH_ADMDT) < 18 THEN 'CHILD'
ELSE NULL
END As AgeGroup,
COUNT(DISTINCT AH_AUTHNO) AS 'Total AFC Admissions',
SUM(DATEDIFF(DD, MIN(AH_ADMDT), MAX(AH_DISDT))) AS 'Total AFC Days',
SUM(AD_UNTAUTH) AS 'Total Units'
FROM
PCHAUHPF AS A
LEFT JOIN
PCHAUDPF AS P
ON A.AH_RCDID = P.ADF_AUHID
JOIN
GTWAUDPF AS G
ON G.ADP_AUDID = P.AD_RCDID
JOIN
PCHCLTPF AS C
ON C.CL_RCDID = A.AHF_CLTID
JOIN
PCHXSPPF AS X
ON X.XP_RCDID = P.ADF_XSPID
JOIN
PCHCPTPF AS T
ON T.CR_RCDID = X.XPF_CPTID
WHERE
AH_ADMDT BETWEEN '10-1-2013' AND '09-30-2014'
AND AD_PAYSTS = 'A'
AND CR_CODE IN ('H2016', 'T1020')
GROUP BY
CASE
WHEN DBO.FN_AGE(CL_DOB, AH_ADMDT) >= 18 THEN 'ADULT'
WHEN DBO.FN_AGE(CL_DOB, AH_ADMDT) < 18 THEN 'CHILD'
ELSE NULL
END
答案 0 :(得分:1)
据推测,您想要的表达式是以下之一:
SUM(DATEDIFF(DAY, AH_ADMDT, AH_DISDT)) AS [Total AFC Days],
或:
DATEDIFF(DAY, MIN(AH_ADMDT), MAX(AH_DISDT)) AS [Total AFC Days],
关于样式问题,我建议您使用单引号仅表示字符串和日期常量(而不是列别名)。并且,在使用datediff()
时使用完整日期部件名称。这样,你(或其他人)不必费力地记住MM
是否持续数月或数分钟。
答案 1 :(得分:0)
以下是评论中我的建议的一个简单示例:
WITH cte AS (
SELECT
MyGroupCol
, MIN(MyDateCol) AS MinDate
, MAX(MyDateCol) AS MaxDate
FROM MyTables
WHERE SomeConditions=true
GROUP BY MyGroupCol
)
SELECT
MyGroupCol
, SUM(DateDiff(dd, MinDate, MaxDate))
FROM cte
GROUP BY MyGroupCol