sql server 某一列求和



SELECT 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) as 日期, count(distinct 就診人次) as 就診人次--SUM(就診人數) AS 就診人數 FROM dbo.[V_SeePeople] WHERE STUDY_DATE >= '2019-12-04 00:00:00.000' and STUDY_DATE <= '2019-12-11 23:59:59.000' and OFDEPARTMENT ='FSK' and ORGNIZATIONCODE ='0101' GROUP BY 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) --order by convert(char(10),STUDY_DATE,121) UNION all select '' ,'' ,'' ,'','合計' ,sum( convert(int,temp.就診人次))AS 就診人次 from ( SELECT top 100 percent 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) as 日期, count(distinct 就診人次) as 就診人次--SUM(就診人數) AS 就診人數 FROM dbo.[V_SeePeople] WHERE STUDY_DATE >= '2019-12-04 00:00:00.000' and STUDY_DATE <= '2019-12-11 23:59:59.000' and OFDEPARTMENT ='FSK' and ORGNIZATIONCODE ='0101' GROUP BY 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) --order by convert(char(10),STUDY_DATE,121) ) as temp
SELECT 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) as 日期, count(distinct 就診人次) as 就診人次--SUM(就診人數) AS 就診人數 FROM dbo.[V_SeePeople] WHERE STUDY_DATE >= '2019-12-04 00:00:00.000' and STUDY_DATE <= '2019-12-11 23:59:59.000' and OFDEPARTMENT ='FSK' and ORGNIZATIONCODE ='0101' GROUP BY 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) --order by convert(char(10),STUDY_DATE,121) UNION all select '' as 患者來源,'' as 設備類型,'' as 檢查部位,''as 設備名稱,'合計' as 日期,sum( convert(int,temp.就診人次))AS 就診人次 from ( SELECT top 100 percent 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) as 日期, count(distinct 就診人次) as 就診人次--SUM(就診人數) AS 就診人數 FROM dbo.[V_SeePeople] WHERE STUDY_DATE >= '2019-12-04 00:00:00.000' and STUDY_DATE <= '2019-12-11 23:59:59.000' and OFDEPARTMENT ='FSK' and ORGNIZATIONCODE ='0101' GROUP BY 患者來源,設備類型,檢查部位,設備名稱,convert(char(10),STUDY_DATE,121) --order by convert(char(10),STUDY_DATE,121) ) as temp
注意:sql 存儲 中 select '' == select ''''
eg:
set @sqlstr2 = ' UNION all select '''' ,'''' ,'''' ,'''' ,''合計'',sum( convert(int,temp.就診人數))AS 就診人數
from (SELECT top 100 percent '+@SelectName+@sdate+' as 日期,
count(distinct 就診人數) as 就診人數 FROM dbo.[V_SeePeople] WHERE
'+@sDateColum+' >= '''+ @sStartDate+' 00:00:00' +''' and '+@sDateColum+' <= ''' +@sEndDate+' 23:59:59'+''' '+@sMod+'
GROUP BY '+@GroupName + @sdate + ') as temp' ;
