我知道我想要数据显示什么,但似乎无法找出正确的逻辑。下面的示例。
数据集
**'ID', 'Admission Mth', 'Admission Yr', 'Category', 'Facility', 'ID_Yr_Cat', 'ID_Yr_Cat_Fac',**
'123456', 'Jan', '2017', 'Hospital', 'NYMC', '123456-2017-Hospital', '123456-2017-Hospital-NYMC',
'123456', 'Jul', '2017', 'Hospital', 'NYMC', '123456-2017-Hospital', '123456-2017-Hospital-NYMC',
'123456', 'Oct', '2018', 'Hospital', 'NYMC', '123456-2018-Hospital', '123456-2018-Hospital-NYMC',
'123456', 'Nov', '2018', 'Hospital', 'NJMC', '123456-2018-Hospital', '123456-2018-Hospital-NJMC',
'789123', 'Feb', '2017', 'Clinic', 'Philly Clinic', '789123-2017-Clinic', '789123-2017-Clinic-Philly Clinic',
'987654', 'May', '2018', 'Hospital', 'PAMC', '987654-2018-Hospital', '987654-2018-Hospital-PAMC',
'456123', 'Sept', '2017', 'Clinic', 'Philly Clinic', '456123-2017-Clinic', '456123-2017-Clinic-Philly Clinic',
'456123', 'Aug', '2018', 'Hospital', 'NYMC', '456123-2018-Hospital', '456123-2018-Hospital-NYMC',
'456123', 'Nov', '2018', 'Hospital', 'NYMC', '456123-2018-Hospital', '456123-2018-Hospital-NYMC',
'456123', 'Dec', '2018', 'Hospital', 'NJMC', '456123-2018-Hospital', '456123-2018-Hospital-NJMC'
我希望最终结果在医院重新入学时显示“ 1”标记。
最终结果应显示:
**'Hospital Readmit per Yr'**,
'0',
'1',
'0',
'1',
'0',
'0',
'0',
'0',
'1',
'1'
**'Hospital Readmit per Yr & Fac'**,
'0',
'1',
'0',
'0',
'0',
'0',
'0',
'0',
'1',
'0'
我的想法是在使用带有分区的前导功能时使用某种情况。只是不确定如何写出来。我正在使用SQL Server MS 2008。
答案 0 :(得分:1)
这可以通过CASE WHEN或LEAD或LAG功能来实现。但是,由于您提到使用的是SQL Server 2008,所以LEAD或LAG可能不起作用,因为LEAD和LAG是可以在SQL Server 2012或更高版本中使用的分析功能。如果要使用CASE WHEN,则可能需要尝试类似的事情。
要获取[每年的医院再入院]标志值:
SELECT
CASE WHEN A.[RowNumber]>1 THEN 1 else 0 END As [Hospital Readmit per Yr]
FROM (select ROW_NUMBER() OVER (PARTITION BY [ID_Yr_Cat] order by [Admission Mth], [Admission Yr]) as [RowNumber], * from hospital) as A
要获取[ID_Yr_Cat_Fac]标志值:
SELECT
CASE WHEN A.[RowNumber]>1 THEN 1 else 0 END As [Hospital Readmit per Yr & Fac]
FROM (select ROW_NUMBER() OVER (PARTITION BY [ID_Yr_Cat_Fac] order by [Admission Mth], [Admission Yr]) as [RowNumber], * from hospital) as A