【问题标题】:Issue using datasets from different databases in a summary SSRS report在摘要 SSRS 报告中使用来自不同数据库的数据集的问题
【发布时间】:2026-01-10 17:40:01
【问题描述】:

我有一个报告来显示用户的摘要,从 2 个数据库中获取数据。我编写了单独的数据集来为每一列获取它, 但由于值可能重复,我不知道如何获取每个用户的所有记录

我在查询中使用 UNION ALL 从 2 个数据库中获取数据

主数据集

Select Count(*) as total, Username from database1
where my condition...
group by Username   
UNION ALL
Select Count(*) as total, Username from database2
where my condition...
group by Username 

Username    Total
User1       2  
User2       1  
User3       3
User4       4
User5       10
User6       5

数据集 2

Select Count(*) as totalCol2, Username from database1
where condition for this column...
group by Username   
UNION ALL
Select Count(*) as totalCol2, Username from database2
where condition for this column...
group by Username 

Username    totalCol2
User1       2  
User2       1  
User2       1  
User3       3  
User3       2  
User4       1  
User5       2  
User5       3  
User6       4  

我使用MainDataset 来显示我的报告中的行,对于每一列我需要显示来自Dataset2 的摘要:

Username    Total   totalCol2
User1       2   2  
User2       1   2  
User3       3   5
User4       4   1
User5       10  5
User6       5   4

我尝试使用查找,但只从 dataset2 中获得了第一个匹配项,求和函数与条件但效果不佳。 有人可以给我一些想法,如果我可以在 SSRS 中做点什么。

报告有超过 10 列,每一列来自不同的数据集。

【问题讨论】:

    标签: sql-server-2008 reporting-services ssrs-2008


    【解决方案1】:

    最简单的答案是更改数据集的查询,使其不返回多行:合并查询中的行。

    真正简单的版本是将您现有的 Dataset2 查询包装在外部 Select ... Group By 中:

    稍微修改了Dataset2:

    SELECT
       Username,
       SUM(totalCol2) as totalCol2
    FROM
    (
       SELECT Count(*) AS totalCol2, Username FROM database1
       WHERE condition for this column...
       GROUP BY Username   
       UNION ALL
       SELECT Count(*) AS totalCol2, Username FROM database2
       WHERE condition for this column...
       GROUP BY Username
    ) AS tableA
    GROUP BY Username
    

    稍微大一点的重写会给你:

    SELECT
       Username,
       COUNT(*) AS totalCol2
    FROM
       (SELECT UserName FROM database1
        WHERE Condition
        UNION ALL
        SELECT UserName FROM database2
        WHERE Condition
        ) AS tableA
     GROUP BY Username
    

    上述任何一个查询都可以很好地与查找功能配合使用。

    但是如果你的 database1 和 database2 对于所有十个查询都是相同的,那么我会尝试将它们组合起来。可能是这样的:

    SELECT
       Username,
       SUM(Col1) AS totalCol1,
       SUM(Col2) AS totalCol2,
       ...
    FROM
       (SELECT
          UserName,
          CASE WHEN [columns meet condition for Col1]
           THEN 1 ELSE 0 END AS Col1,
          CASE WHEN [test for condition of Column2]
           THEN 1 ELSE 0 END AS Col2,
          ... 
        FROM database1
    
        UNION ALL
        SELECT
          UserName,
          CASE WHEN [columns meet condition for Col1]
           THEN 1 ELSE 0 END AS Col1,
          CASE WHEN [test for condition of Column2]
           THEN 1 ELSE 0 END AS Col2,
          ... 
        FROM database2
        ) AS tableA
     GROUP BY Username
    

    【讨论】:

    • 感谢 Jamie,现在工作!我只测试了 2 个数据集,我现在将去测试更多!
    最近更新 更多