SQLserver一年最后一天零点数据减去一年第一天零点数据做差,如果数据库空则显示0

SQL server 一年的最后一天零点数据减去一年第一天零点数据做差,如果数据库空则显示0

FineReport LBJ23 发布于 2024-2-11 17:48
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共2回答
最佳回答
0
姬迷怎滴Lv5初级互助
发布于2024-2-12 12:44(编辑于 2024-2-21 08:59)

SELECT

    COALESCE(

        (SELECT data_column

         FROM your_table

         WHERE CAST(your_date_column AS DATE) = CAST(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS DATE)  -- 当年第一天

        ), 0) -

    COALESCE(

        (SELECT data_column

         FROM your_table

         WHERE CAST(your_date_column AS DATE) = CAST(DATEADD(yy, DATEDIFF(yy, -1, GETDATE()), -1) AS DATE)  -- 当年最后一天

        ), 0) AS difference

  • LBJ23 LBJ23(提问者) 您这是日期做差?我需要的是数据做差值,数据为空则显示0
    2024-02-20 10:58 
最佳回答
0
用户bBKn44909079Lv3见习互助
发布于2024-2-21 15:45

with t1 as (

  select cast('20240101 00:00:00' as datetime) as fdate,56 as fnum

union all

select cast('20241231 00:00:00' as datetime) as fdate,36 as fnum

union all

select cast('20240221 00:00:00' as datetime) as fdate,68 as fnum

union all

select cast('20240518 00:00:00' as datetime) as fdate,19 as fnum

union all

select cast('20240815 00:00:00' as datetime) as fdate,82 as fnum

union all

select cast('20240423 00:00:00' as datetime) as fdate,73 as fnum)

select

  --当年最后一天零点

  sum(case when fdate=dateadd(year,datediff(year,0,dateadd(year,1,getdate())),-1) and fnum is not null then fnum else 0 end) -

--当年第一天零点

  sum(case when fdate=dateadd(yy,datediff(yy,0,getdate()),0) and fnum is not null then fnum else 0 end) as fcz

from t1

  • 2关注人数
  • 409浏览人数
  • 最后回答于:2024-2-21 15:45
    请选择关闭问题的原因
    确定 取消
    返回顶部