我有一份报告显示用户摘要,从2个数据库中获取数据。我编写了单独的数据集来获取每列, 但由于价值可能会重复,我不知道如何获得每个用户的所有记录
我在查询中使用UNION ALL
来从2个数据库中获取数据
MainDataset
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的第一个匹配,sum函数与条件但不起作用。 有人可以告诉我是否能在SSRS中做些什么。
该报告有10多个列,每个列来自不同的数据集。
答案 0 :(得分:0)
最简单的答案是更改数据集的查询,以便它们不返回多行:合并查询中的行。
真正简单的版本就是将现有的Dataset2查询包装在外部Select ... Group By:
略微修订的数据集2:
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