将SSRS与SQL Server 2008 R2一起使用(Visual Studio环境)。
我正在尝试根据sql server上的表中的级别/值生成一个降低报告。该级别充当缩进位置,sort_value是报表中的递归父级。
SQL Server中的表示例:
需要输出的样本
答案 0 :(得分:0)
好的,我已经提出了解决方案,但请注意以下,然后再继续。 1.根据您的样本数据,该过程依赖于数据的正确顺序。 2.如果这是您真实的数据结构,我强烈建议您查看它。
好的,所以我做的第一件事就是按照例子完全重新创建你的表格。我打电话给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