创建因条件而异的多个计数

时间:2018-11-09 21:31:49

标签: sql select count where multiple-columns

我有一个运行良好的简单查询,但是我需要运行它,以每12个月*几年的时间更改“条件”语句。我想产生12列,每列代表该月的计数;如果此数据以某种方式在行中表示,那也是可以接受的。

当前查询:

SELECT  
    field1
    ,field2
    ,field3
      ,count(distinct(table1.field4))   

  FROM table1   
  inner join table2 
  on table1.field4=table2.field4
  where  year_month <=201808

group by    
    field1
    ,field2
    ,field3

order by    
    field1
    ,field2
    ,field3

1 个答案:

答案 0 :(得分:0)

去那里:

DECLARE @year INT,
    @i INT = 1,
    @date VARCHAR(6),
    @month INT = 1,
    @months INT = 12,
    @sql NVARCHAR(MAX)

DECLARE @years TABLE (
    Id INT IDENTITY,
    myYear INT
)

INSERT INTO @years (myYear)
VALUES (2016),
    (2017),
    (2018)

CREATE TABLE #table (
    field1 [your data type],
    field2 [your data type],
    field3 [your data type],
    myDate VARCHAR(6),
    myCount INT
)

WHILE @i <= (SELECT MAX(Id) FROM @years)
BEGIN
    SELECT @year = myYear
    FROM @years
    WHERE Id = @i

    WHILE @month <= @months
    BEGIN
        IF @month < 10
            SET @date = @year + '0' + CAST(@month as VARCHAR(2))
        ELSE
            SET @date = @year + CAST(@month as VARCHAR(2))

        SET @sql = 'INSERT INTO #table SELECT field1 ,field2 ,field3, year_month as myDate, count(distinct(table1.field4)) as myCount 
            FROM table1 JOIN table2 ON table1.field4 = table2.field4
            WHERE year_month = ''' + CAST(@date AS NVARCHAR(MAX)) + ''' GROUP BY field1, field2, field3, year_month ORDER BY year_month, field1, field2, field3'

        EXECUTE sp_executesql @sql

        SET @month = @month + 1
    END

    SET @month = 1
    SET @i = @i + 1
END

SELECT * FROM #table

DROP TABLE #table