如何使用sql server获取最近6个月的数据与时间戳列进行比较

如何使用sql server获取最近6个月的数据与时间戳列进行比较,sql,sql-server-2012,Sql,Sql Server 2012,我想显示过去6个月(包括本月)的捕获量、monthname和monthvalue,如果任何月份没有捕获量,只需显示monthname和0值,例如: 数据: 我有疑问 SELECT COUNT(CaughtId) as catches, MONTH(DATEADD(mm, -6, GETDATE())) AS MonthValue ,LEFT(DATENAME(mm, DATEADD(mm, -6, GETDATE())), 3) AS MonthText FROM [dbo].[Catches

我想显示过去6个月(包括本月)的捕获量、monthname和monthvalue,如果任何月份没有捕获量,只需显示monthname和0值,例如:

数据:

我有疑问

SELECT COUNT(CaughtId) as catches, MONTH(DATEADD(mm, -6, GETDATE())) AS MonthValue ,LEFT(DATENAME(mm,  DATEADD(mm, -6, GETDATE())), 3) AS MonthText FROM [dbo].[Catches] fct WHERE fct.[TripId] IN
    (SELECT TripId FROM [dbo].[Trips] WHERE UserId = 'e406d452-3755-4dbb-99a9-1f01df60d842')
    AND fct.Timestamp >= dateadd(month,-6,dateadd(day,datediff(day,0,getdate()),1)) 
通过以上查询,我得到的结果低于输出

catch   monthvalue   monthname
20         12           Dec

您可以尝试使用此查询:

with dates as (
  select dateadd(month,-5,convert(datetime,convert(varchar,getdate(),112),112)) as datefield
  union all
  select dateadd(month,1,datefield) from dates
  where datefield + 1 <= convert(datetime,convert(varchar,getdate(),112),112)
  )  
,your_data as (
  select 5 as mnt,  10 as catches union all
  select 4 as mnt,  12 as catches union all
  select 6 as mnt,  0 as catches
  )
select datename(month,d.datefield) as MonthName,
  month(d.datefield) as MonthNumber,
  isnull(yd.catches,0) as catches
from dates d
  left join your_data yd
    on month(d.datefield)=yd.mnt
option (maxrecursion 0)
输出:


要做到这一点,您需要使用某个表进行连接,在该表中存在您想要创建的所有月份,因此您可以对该表执行左连接操作,以便在该月份没有数据时显示0。我在查询中没有看到任何与JSON相关的函数,因此我猜您的表中有明确的数据。所以请不要将其作为JSON发布,使用INSERT INTO语句显示表数据以及表的CREATE table语句。
with dates as (
  select dateadd(month,-5,convert(datetime,convert(varchar,getdate(),112),112)) as datefield
  union all
  select dateadd(month,1,datefield) from dates
  where datefield + 1 <= convert(datetime,convert(varchar,getdate(),112),112)
  )  
,your_data as (
  select 5 as mnt,  10 as catches union all
  select 4 as mnt,  12 as catches union all
  select 6 as mnt,  0 as catches
  )
select datename(month,d.datefield) as MonthName,
  month(d.datefield) as MonthNumber,
  isnull(yd.catches,0) as catches
from dates d
  left join your_data yd
    on month(d.datefield)=yd.mnt
option (maxrecursion 0)