我想显示过去6个月(包括当月)的捕获量,月份值和月份值,如果任何月份没有任何捕获量只显示月份名称和0值为ex:
数据:
[
{
"monthText": "May",
"monthInt": 5,
"Catches": 10
},
{
"monthText": "April",
"monthInt": 4,
"Catches": 12
},
{
"monthText": "June",
"monthInt": 6,
"Catches": 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
答案 0 :(得分:-1)
您可以尝试使用此查询:
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)
输出: