--病人年龄分布统计
CREATE PROCEDURE sp_StudyAgeLoad
    @ModalityType varchar(18), 
    @StatStartDttm datetime,
    @StatEndDttm datetime 
AS
BEGIN
 
DECLARE @sStudy_dttm datetime 
DECLARE @iStudy_key int
DECLARE @sGroupField varchar(128)
DECLARE @sStatistField varchar(128)
DECLARE @fStatistWeight money
DECLARE @iPos int
DECLARE @ilen int
-- 病人所属年龄组
DECLARE @iAgeGroup int


DECLARE crStudy CURSOR FOR

SELECT study_dttm, study_key, study_bodypart, floor(dateDiff(yyyy, patient_birthday, study_dttm)/10)*10
FROM study
WHERE study_modalitytype=@ModalityType AND report_state > 0 AND
	study_dttm >= @StatStartDttm AND study_dttm <= @StatEndDttm 

OPEN crStudy

FETCH NEXT FROM crStudy 
INTO @sStudy_dttm, @iStudy_key, @sGroupField, @iAgeGroup

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @sGroupField=RTRIM(LTRIM(@sGroupField))  
  IF LEN(@sGroupField) > 0
  BEGIN
	  SET @iPos=CHARINDEX(' ',@sGroupField)          
	  WHILE @iPos>=1       
	  BEGIN    
		SET @sStatistField=SUBSTRING(@sGroupField,1,@iPos-1)  
		INSERT INTO CC_Statist (study_dttm,statist_field,statist_weight,tmp_AgeGroup)
			VALUES(@sStudy_dttm,@sStatistField,1,@iAgeGroup)
		SET @iLen=LEN(@sGroupField)  
		SET @sGroupField=SUBSTRING(@sGroupField,@iPos+1,@iLen)  
		SET @sGroupField=RTRIM(LTRIM(@sGroupField))  
		SET @iPos=CHARINDEX(' ',@sGroupField)  
	  END

	  INSERT INTO CC_Statist (study_dttm,study_key,statist_field,statist_weight,tmp_AgeGroup)
		VALUES(@sStudy_dttm,@iStudy_key,@sGroupField,1,@iAgeGroup)    
  END
  	
  FETCH NEXT FROM crStudy 
  INTO @sStudy_dttm,@iStudy_key,@sGroupField,@iAgeGroup
END       

CLOSE crStudy     
DEALLOCATE crStudy 

-- 按部位权重更新cc_statist，仅更新权重不为1的部位，如果dd_bodypart中的权重设为负数，则权重为0
DECLARE crBodyPart CURSOR FOR       
SELECT bodypart_name,CASE WHEN bodypart_charge1>0.0 THEN bodypart_charge1 ELSE 0.0 END       
FROM dd_bodypart WHERE modality_type=@ModalityType AND (bodypart_charge1<1.0 OR bodypart_charge1>1.0)

OPEN crBodyPart      

FETCH NEXT FROM crBodyPart  
INTO @sStatistField,@fStatistWeight 

WHILE @@FETCH_STATUS=0 
BEGIN 
  UPDATE cc_statist SET statist_weight=@fStatistWeight WHERE statist_field=@sStatistField 
  
  FETCH NEXT FROM crBodyPart  
  INTO @sStatistField,@fStatistWeight
END 

CLOSE crBodyPart
DEALLOCATE crBodyPart

END