3

我有一些来自数据库的数据,但今年只有 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   |

所有的“数字”都是那些不是从数据库中提取的,只是我想放的东西

建议?

4

1 回答 1

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

在此处查看功能示例。

于 2013-07-18T22:50:11.687 回答