我正在编写一个应该给我一个count()
和三个avg()
的查询。 count()
工作正常,但avg()
函数返回错误结果。我正在使用的数据如下所示:
MD Name | PT | Med Staff | LOS | DRG Bench | LOS - Bench
MCP | 12345 | Ortho SX | 5 | 4 | 1
MCP | 25879 | Ortho SX | 3 | 5 | -2
MCP | 98556 | Ortho SX | 4 | 5 | -1
...
我想要的输出是:
MD Name | # PT | Med Staff | Avg LOS | Avg DRG Bench | AVG LOS - Bench
MCP | 3 | Ortho SX | 4 | 4.66 | 0
我得到的平均值不正确。我有一个案例,特别是我有以下内容:
MD Name | LOS | Bench | LOS - Bench
MCP | 2.0000 | 1.8000 | 0.2000
MCP | 1.0000 | 1.7000 | -0.7000
MCP | 25.0000| 4.9000 | 20.1000
MCP | 4.0000 | 2.2000 | 1.8000
对于和AVG LOS我得到9.000000而不是8.000000,对于AVG Bench我得到2.780000而不是2.65而对于LOS-Bench我得到6.220000而不是5.35,这些是显着的差异我必须是正确的两位小数。
这是我正在使用的SQL,SQL Server 2008
DECLARE @STARTDATE DATETIME
DECLARE @ENDATE DATETIME
SET @STARTDATE = '2013-05-01'
SET @ENDATE = '2013-05-31'
SELECT DISTINCT pv.pract_rpt_name AS 'PHYSICIAN'
, COUNT(DISTINCT vr.pt_id) AS '# PTS'
--, pv.spclty_desc AS 'SPECIALTY'
, pv.med_staff_dept AS 'MED STAFF'
, AVG(vr.len_of_stay) AS 'LOS'
, AVG(vr.drg_std_days_stay) AS 'DRG LOS BENCH'
, AVG(vr.len_of_stay - vr.drg_std_days_stay) AS 'LOS - DRG BENCH'
FROM smsmir.vst_rpt vr
LEFT OUTER JOIN smsmir.pyr_plan pp <-- removed and fixed
ON vr.pt_id = pp.pt_id <-- removed and fixed
JOIN smsdss.pract_dim_v pv
ON vr.adm_pract_no = pv.src_pract_no
WHERE vr.adm_dtime BETWEEN @STARTDATE AND @ENDATE
AND vr.vst_type_cd = 'I'
AND pv.spclty_desc != 'NO DESCRIPTION'
--AND pv.spclty_desc NOT LIKE 'HOSPITALIST%'
AND vr.drg_std_days_stay IS NOT NULL
AND pv.pract_rpt_name != '?'
AND pv.orgz_cd = 's0x0'
AND pv.med_staff_dept IN (
'INTERNAL MEDICINE',
'FAMILY PRACTICE',
'SURGERY'
)
GROUP BY pv.pract_rpt_name, pv.med_staff_dept
ORDER BY pv.med_staff_dept, AVG(vr.len_of_stay - vr.drg_std_days_stay)DESC
感谢您的时间和精力。
答案 0 :(得分:1)
查询中的OUTER JOIN可能会影响AVG功能正在运行的行数。如果您不需要它(我无法看到您的查询中其他地方引用该表的任何地方)尝试删除它。
答案 1 :(得分:1)
唯一的可能性是在表中的行中存在NULL选择... 如果有一个空列,AVG将忽略它,而不是计算它......
DECLARE @STARTDATE DATETIME
DECLARE @ENDATE DATETIME
SET @STARTDATE = '2013-05-01'
SET @ENDATE = '2013-05-31'
SELECT DISTINCT pv.pract_rpt_name AS 'PHYSICIAN'
, COUNT(DISTINCT vr.pt_id) AS '# PTS'
--, pv.spclty_desc AS 'SPECIALTY'
, pv.med_staff_dept AS 'MED STAFF'
, AVG(ISNULL(vr.len_of_stay,0)) AS 'LOS'
, AVG(ISNULL(vr.drg_std_days_stay,0)) AS 'DRG LOS BENCH'
, AVG(ISNULL((vr.len_of_stay - vr.drg_std_days_stay),0)) AS 'LOS - DRG BENCH'
FROM smsmir.vst_rpt vr
LEFT OUTER JOIN smsmir.pyr_plan pp
ON vr.pt_id = pp.pt_id
JOIN smsdss.pract_dim_v pv
ON vr.adm_pract_no = pv.src_pract_no
WHERE vr.adm_dtime BETWEEN @STARTDATE AND @ENDATE
AND vr.vst_type_cd = 'I'
AND pv.spclty_desc != 'NO DESCRIPTION'
--AND pv.spclty_desc NOT LIKE 'HOSPITALIST%'
AND vr.drg_std_days_stay IS NOT NULL
AND pv.pract_rpt_name != '?'
AND pv.orgz_cd = 's0x0'
AND pv.med_staff_dept IN (
'INTERNAL MEDICINE',
'FAMILY PRACTICE',
'SURGERY'
)
GROUP BY pv.pract_rpt_name, pv.med_staff_dept
ORDER BY pv.med_staff_dept, AVG(vr.len_of_stay - vr.drg_std_days_stay)DESC