我有一些来自数据库的数据,但今年只有4个月。我希望它能全部退回12个月。我使用的是Sql Server Management Studio 2010.这是sql代码
SELECT Month = datename(month,dateadd(mm,datediff(mm,0,StartTime),0)), Count (TestName)
FROM VExecutionGlobalHistory
Where Tester <> 'dit2988'
group by
dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
order by
dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
此返回
|April|92 |
|May |79 |
|June |164 |
|July |162 |
我想在回程中添加一些硬编码数据,并将7月作为最新数据,所以我会有类似的东西。
|August |number|
|September|number|
|October |number|
|November |number|
|December |number|
|January |number|
|February |number|
|March |number|
|April |92 |
|May |79 |
|June |164 |
|July |162 |
其中所有“数字”都是不从数据库中提取的数字,只是我要放的东西
建议?
答案 0 :(得分:2)
只需创建一个从初始日期到最终日期的计数,然后按月份数和年份对数据进行左连接:
DECLARE @start_date DATETIME, @end_date DATETIME;
SELECT @start_date = CAST('2010-08-01' AS DATETIME),
@end_date = CAST('2011-07-01' AS DATETIME);
WITH MonthTally(initial_date,month_name, month_number, year_number) AS
(
SELECT @start_date initial_date, datename(month,@start_date) month_name, month(@start_date) month_number, year(@start_date) year_number
UNION ALL
SELECT DATEADD(month,1,initial_date), datename(month, DATEADD(month,1,initial_date)), month(DATEADD(month,1,initial_date)), year(DATEADD(month,1,initial_date))
FROM MonthTally
WHERE initial_date < @end_date
)
SELECT month_name, Count(TestName)
FROM MonthTally MT
LEFT JOIN VExecutionGlobalHistory V ON MT.year_number=YEAR(V.StartTime) AND MT.month_number=MONTH(V.StartTime) AND Tester <> 'dit2988'
group by
month_name, year_number, month_number
order by
year_number, month_number
检查功能示例here。