返回另一个表中指定的帐户总数的查询,其中定义了总计或范围的帐户

时间:2017-04-07 19:32:13

标签: sql tsql sql-server-2016

我有一个用户正在维护的表,他们在哪里。统计帐户可以定义他们想要总结的帐户 - 无论是指定的还是范围的。如何构建最能总结pr stat帐户和月份金额的视图。我需要以某种方式pr。帐户可以更改where子句。

下面我有两个表:DimStatAccount和FactAmount及以下是预期的视图

Show input tables and expected output view

2 个答案:

答案 0 :(得分:2)

我从凯文的回答中偷走了桌子。您可以使用选择变量的功能从DimStatAccount表创建动态SQL select语句。

AutoGeneratingColumns=True

答案 1 :(得分:0)

像已经说过的那样,动态sql就是你所需要的。

CREATE TABLE #dimStatAccount (StatAccount varchar(255), Accounts varchar(255), AccountsRange varchar(255))
INSERT INTO #dimStatAccount VALUES
  ('Stat1', 'in (1000,1020)', null),
  ('Stat2', 'in (1020,2020)', null),
  ('Stat3', null, 'between 1000 and 1999'),
  ('Stat4', null, 'between 2000 and 2999')

CREATE TABLE #factAmount (Account int, [Month] varchar(255), Amount int)
INSERT INTO #factAmount VALUES
  (1000,'jan',500),
  (1000,'feb',460),
  (1010,'jan',799),
  (1010,'jan',855),
  (1010,'feb',633),
  (1020,'feb',522),
  (2000,'jan',436),
  (2000,'jan',946),
  (2000,'jan',374),
  (2010,'jan',683),
  (2010,'feb',492),
  (2020,'jan',437),
  (2020,'feb',834),
  (2030,'jan',944)

CREATE TABLE #result (StatAccount varchar(255), [Month] varchar(255), SumAmount int)

DECLARE @statAccount varchar(255), @accounts varchar(255), @rangeAccounts varchar(255)

DECLARE rcursor CURSOR FOR
  SELECT StatAccount, Accounts, AccountsRange
  FROM #dimStatAccount
OPEN rcursor
FETCH NEXT FROM rcursor
INTO @statAccount, @accounts, @rangeAccounts

WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE @sql NVARCHAR(max)
  IF @accounts IS NOT NULL
  BEGIN
    SET @Sql = 'INSERT INTO #result '
    SET @sql = @Sql + 'SELECT ''' + @statAccount + ''' AS StatAccount, [MONTH], SUM(f.Amount) AS SumAmount '
    SET @Sql = @Sql + 'FROM #factAmount AS f '
    SET @Sql = @Sql +  'WHERE Account ' + @accounts + ' ' 
    SET @Sql = @Sql +  'GROUP BY [Month]'

    EXEC sp_executesql @Sql

    FETCH NEXT FROM rcursor
    INTO @statAccount, @accounts, @rangeAccounts
  END   
  IF @rangeAccounts IS NOT NULL
  BEGIN
    SET @Sql = 'INSERT INTO #result '
    SET @sql = @Sql + 'SELECT ''' + @statAccount + ''' AS StatAccount, [MONTH], SUM(f.Amount) AS SumAmount '
    SET @Sql = @Sql + 'FROM #factAmount AS f '
    SET @Sql = @Sql +  'WHERE Account ' + @rangeAccounts + ' ' 
    SET @Sql = @Sql +  'GROUP BY [Month]'
    print @Sql
    EXEC sp_executesql @Sql

    FETCH NEXT FROM rcursor
    INTO @statAccount, @accounts, @rangeAccounts
  END
END

CLOSE rcursor 
DEALLOCATE rcursor 

SELECT * FROM #result

结果

StatAccount  Month  SumAmount
-----------------------------
Stat1        feb    982
Stat1        jan    500
Stat2        feb    1356
Stat2        jan    437
Stat3        feb    1615
Stat3        jan    2154
Stat4        feb    1326
Stat4        jan    3820