我的查询是跟踪“患者日”或患者(csn_id)进入并离开同一天。这种情况以两种方式之一发生
在我添加Group By语句之前,一切看起来都很好。我已经阅读了收到相同“Msg 8120”的其他问题帖子,但我不确定我如何解决这个问题并对任何/所有建议持开放态度。
SELECT
'1,*'+char(13)+char(10)
+'80,1006057'+char(13)+char(10)
+'100,10'+char(13)+char(10)
+'2405,'+cast(count(distinct adt.PAT_ENC_CSN_ID) as varchar(18))+char(13)+char(10) --Census events --as varchar(10)
+'2420,'+format(adt.EFFECTIVE_TIME,'M/d/yyyy') --as efftime
FROM CLARITY_ADT adt
inner join PAT_ENC_HSP hsp on adt.PAT_ENC_CSN_ID=hsp.PAT_ENC_CSN_ID
WHERE adt.EVENT_SUBTYPE_C <>2 AND --no canelled events
datediff(day,adt.EFFECTIVE_TIME,cast(CURRENT_TIMESTAMP as date)) between 1 and 7 AND
((adt.EVENT_TYPE_C ='6' AND
adt.DEPARTMENT_ID in ('101000020', '101000021', '101000013', '101000014', '101000002',
'101000018', '101000003', '101000114', '101000005', '101000017',
'101000006', '101000118', '101000007', '101000016', '101000004',
'101000009', '101000010', '101000011', '101000022', '101000023',
'101000012')) OR
(cast(hsp.HOSP_ADMSN_TIME as date) = cast(hsp.HOSP_DISCH_TIME as date) AND
adt.EVENT_TYPE_C ='1' AND
adt.DEPARTMENT_ID in ('101000020', '101000021', '101000013', '101000014', '101000002',
'101000018', '101000003', '101000114', '101000005', '101000017',
'101000006', '101000118', '101000007', '101000016', '101000004',
'101000009', '101000010', '101000011', '101000022', '101000023',
'101000012')))
group by cast(adt.EFFECTIVE_TIME as date)
order by cast(adt.EFFECTIVE_TIME as date)
答案 0 :(得分:0)
当您执行group by
时,您唯一允许在查询结果中使用的是组本身或max
或sum
等聚合。< / p>
您按cast(adt.EFFECTIVE_TIME as date)
进行分组,但您的查询包含format(adt.EFFECTIVE_TIME,'M/d/yyyy')
- 虽然这些可能在逻辑上是等效的,但它们并不相同,因此SQL Server会告诉您你觉得它不好。
您可以将format(adt.EFFECTIVE_TIME,'M/d/yyyy')
放入group by
,或者将日期放入查询可能会更好,然后使用外部查询对其进行换行以格式化您的结果:
select
'1,*'+char(13)+char(10)
+'80,1006057'+char(13)+char(10)
+'100,10'+char(13)+char(10)
+'2405,'+cast(num_records as varchar(18))+char(13)+char(10) --Census events --as varchar(10)
+'2420,'+format(the_date,'M/d/yyyy') --as efftime
from
(
select
cast(adt.EFFECTIVE_TIME as date) [the_date]
,count(distinct adt.PAT_ENC_CSN_ID) [num_records]
FROM CLARITY_ADT adt
WHERE ... /* where and join clauses */
group by cast(adt.EFFECTIVE_TIME as date)
) x
order by x.the_date;