季度总计在SQL服务器中使用循环

时间:2014-05-01 22:44:17

标签: sql-server sequel

----我正试图分别为旧金山和圣马泰奥县分别获得2013年和2014年的年度和季度总数。我知道它可能很容易但循环有困难。我可以在没有循环的情况下完成它,但它很长,并且希望以更整洁的方式进行。任何帮助将不胜感激。编程新手------

DECLARE @Qtotal int
DECLARE @Q1total int
DECLARE @Q2total int
DECLARE @Q3total int
DECLARE @Q4total int
DECLARE @year int
DECLARE @County int
DECLARE @CountyName varchar(40)
DECLARE @startmonth nvarchar
DECLARE @endmonth nvarchar

SET @startmonth = '1'
SET @endmonth = '3'
SET @year = '2013'
SET @county = '038'
SET @countyName = 'San Francisco'

Begin
 SELECT @Qtotal = (select COUNT(*) FROM #tCounty 
 where year(cast(dDate as date)) = @year
   and countycode = @County
   and month(cast(deathDate as date)) between @startmonth and @endmonth)--get quarter total
if @startmonth=1 SET @Q1total = @Qtotal
if @startmonth=4 SET @Q2total = @Qtotal
if @startmonth=7 SET @Q3total = @Qtotal
if @startmonth=10 SET @Q4total = @Qtotal

Set @startmonth = @startmonth + 3
Set @startmonth = @endmonth + 3
if @startmonth > 10 
end

--------插入之前创建的表中,而不是在上面的代码中显示

INSERT INTO #Totals([County],[referenceYear],[Total],[Q1],[Q2],[Q3],[Q4]) Values         (@countyName,@year,@yrtotal,@Q1total,@Q2total,@Q3total,@Q4total)

1 个答案:

答案 0 :(得分:1)

这应该做到

select County, 
    Year(dDate) as Year, 
    count(*) as Total, 
    sum(case when DATEPART(q, dDate)=1 then 1 else 0 end) as Q1,
    sum(case when DATEPART(q, dDate)=2 then 1 else 0 end) as Q2,
    sum(case when DATEPART(q, dDate)=3 then 1 else 0 end) as Q3,
    sum(case when DATEPART(q, dDate)=4 then 1 else 0 end) as Q4
from #tCounty
group by County, 
    Year(dDate)