针对以下查询的{6个月}的递归SQL查询

时间:2017-08-22 12:48:51

标签: sql sql-server-2012

我想知道是否有办法以递归方式执行以下查询,因此在最近的6个月中这样做了6次。

SELECT DATENAME(MONTH,GETDATE()) AS 'Month', 
       SUM(CASE WHEN OverallRiskRating = 1 THEN 1 END) AS 'Low',
       SUM(CASE WHEN OverallRiskRating = 2 THEN 1 END) AS 'Med',
       SUM(CASE WHEN OverallRiskRating = 3 THEN 1 END) AS 'High'
FROM dbo.ChangeEvaluationForm
WHERE MONTH(DateSubmitted) = MONTH(GETDATE())

此查询的结果如下

enter image description here

我想在当前月份之前的每个月再返回5行数据。那是可能的吗?如果可以的话,我想避免再执行5次个人查询。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用Private Sub TextBox1_LostFocus() If TextBox1.Text = "secret" Then CheckBox1.Enabled = True End If End Sub Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) If KeyCode = vbKeyReturn Then Cells(1, 1).Select End If End Sub Private Sub CheckBox1_Click() If TextBox1.Text = "secret" Then CheckBox1.Enabled = True Else CheckBox1.Value = False CheckBox1.Enabled = False End If End Sub 并使用GROUP BY从当月开始追溯6个月来执行此操作:

DATEADD()

答案 1 :(得分:-1)

您可以使用递归cte

declare @Date smalldatetime
set @Date = '20170801'

;with cte as 
(
    select @Date as StartMonth

    union all

    select DATEADD(MONTH, -1, StartMonth)
    from cte
    where StartMonth > DATEADD(MONTH, -5, @Date)
)
SELECT DATENAME(MONTH, D) AS 'Month', 
       SUM(CASE WHEN OverallRiskRating = 1 THEN 1 END) AS 'Low',
       SUM(CASE WHEN OverallRiskRating = 2 THEN 1 END) AS 'Med',
       SUM(CASE WHEN OverallRiskRating = 3 THEN 1 END) AS 'High'
FROM dbo.ChangeEvaluationForm
    inner join cte on MONTH(DateSubmitted) = MONTH(StartMonth)