SSRS Stepped 根据数字报告

SSRS Stepped reported based on number

在 SQL Server 2008 R2(Visual Studio 环境)中使用 SSRS。

我正在尝试根据 sql 服务器上 table 中的 level/value 生成降级报告。该级别充当缩进位置,sort_value 是报告中的递归父级。

SQL 服务器中 table 的样本:

需要输出样本

好的,我已经想出了一个解决方案,但是 请在继续之前注意以下内容。 1. 根据您的样本数据,该过程依赖于数据的正确顺序。 2.如果这是你真正的数据结构,我强烈建议你复习一下。

好的,所以我做的第一件事就是完全按照示例重新创建您的 table。我打电话给 table Stepped 因为我想不出别的了!

然后可以将以下代码用作 SSRS 中的数据集,但显然您可以直接 运行 T-SQL 来查看输出。

-- Create a copy of the data with a row number. This means the input data MUST be in the correct order.
DECLARE @t TABLE(RowN int IDENTITY(1,1), Sort_Order int, [Level] int, Qty int, Currency varchar(20), Product varchar(20))

INSERT INTO @t (Sort_Order, [Level], Qty, Currency, Product)
    SELECT * FROM Stepped

-- Update the table so each row where the sort_order is NULL will take the sort order from the row above
UPDATE a SET Sort_Order = b.Sort_Order
 FROM @t a
    JOIN @t b on a.RowN = b.rowN+1
 WHERE a.Sort_Order is null and b.Sort_Order is not null

 -- repeat this until we're done.
WHILE @@ROWCOUNT >0
    BEGIN
        UPDATE a SET Sort_Order = b.Sort_Order
            FROM @t a
                JOIN @t b on a.RowN = b.rowN+1
            WHERE a.Sort_Order is null and b.Sort_Order is not null
    END

-- Now we can select from our new table sorted by both sort oder and level.
-- We also separate out the products based on their level.
SELECT 
        CASE Level WHEN 1 THEN Product ELSE NULL END as ProdLvl_1
        , CASE Level WHEN 2 THEN Product ELSE NULL END as ProdLvl_2
        , CASE Level WHEN 3 THEN Product ELSE NULL END as ProdLvl_3
        , QTY
        , Currency
    FROM @t s
    ORDER BY Sort_Order, Level

输出看起来像这样...

您可能还想考虑为此换掉最终声明。

-- Alternatively use this style and use a single column in the report.
-- This is better if the number of levels can change.
SELECT 
        REPLICATE('--', Level-1) + Product  as Product
        , QTY
        , Currency
    FROM @t s
    ORDER BY Sort_Order, Level

因为这将为您提供 'product' 的单列,缩进方式如下。