如何在SQL中的子查询中组合循环?

时间:2015-10-20 22:58:59

标签: sql sql-server tsql sql-server-2014 sql-server-2014-express

我试图通过循环自动化,我定义了一个开始和结束时间段@t_begin,@ t_end从0到24开始。 当前,我将逐个放入所有这些代码,例如,为了结束t = 60,我需要复制并粘贴60个子查询。

下面重要的是tMONTHS = 0,1,2,......我不想将它们一直复制到t = 24。

SELECT
    (
     SELECT COUNT(CODE) FROM #TEMP
     WHERE (tMONTHS = 0) AND (KANALKODU = @channel) AND (tSTATUS = 2) AND (TARIH < @datelimit)
      ) as T,
     (
     SELECT COUNT(CODE) FROM #TEMP
     WHERE (tMONTHS = 1) AND (KANALKODU = @channel) AND (tSTATUS = 2) AND (TARIH < @datelimit)
     ) as t1,
     (
     SELECT COUNT(CODE) FROM #TEMP
     WHERE (tMONTHS = 2) AND (KANALKODU = @channel) AND (tSTATUS = 2) AND (TARIH < @datelimit)
     ) as t2,
    (
     SELECT COUNT(CODE) FROM #TEMP
     WHERE (tMONTHS = 3) AND (KANALKODU = @channel) AND (tSTATUS = 2) AND (TARIH < @datelimit)
    ) as t3; 
GO

1 个答案:

答案 0 :(得分:1)

首先创建一个数字表。这个数字代表几个月,几天,你需要的任何东西。

SELECT TOP 10000 N=IDENTITY(INT, 0, 1)
INTO dbo.Numbers
FROM master.dbo.syscolumns a CROSS JOIN master.dbo.syscolumns  b;

我建议您阅读此帖以获取更多信息https://dba.stackexchange.com/questions/11506/why-are-numbers-tables-invaluable

然后创建每个月的列表

      SELECT COUNT(tMONTHS ) as code_count, tMONTHS as month FROM #TEMP CROSS JOIN Numbers
        WHERE (tMONTHS = n) AND (KANALKODU = @channel) AND 
           (tSTATUS = 2) AND (TARIH < @datelimit)   
             AND n BETWEEN @t_begin AND @t_end

这个结果集每月带来一行,有两列,code_count和month。现在你可以PIVOT。

注意:我要晚餐,以后再见