【问题标题】:Quarterly totals using loop in SQL server在 SQL Server 中使用循环的季度总计
【发布时间】:2014-05-01 22:44:17
【问题描述】:

----我正在尝试分别获得旧金山和圣马特奥县 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)

【问题讨论】:

    标签: sql sql-server


    【解决方案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)
    

    【讨论】:

    • 哇,谢谢,工作完美,比我做的简单多了!
    • @vfiola - 很高兴它有帮助。如果您同意,请接受此答案,以便结束问题。
    • 我还有一个问题,如何将总计添加到底部,以添加两个县的总数并添加两个县的四分之一。我试过汇总但没有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多