2012-02-16 74 views
1

我有一個報告,顯示用戶的總結,從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的第一場比賽,和函數有條件但不起作用。 有人可以給我一些想法,如果我可以做一些SSRS。

報告有10多列,並從型動物數據集來每一個。

回答

0

最簡單的答案是改變你的查詢您的數據集,這樣他們就不會返回多行:在您的查詢相結合的行。

這樣做的很簡單的版本是隻包裝現有的查詢Dataset2在外部選擇... 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 

上述任何一種查詢都可以很好地使用查找功能。

但是如果你的數據庫1和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 
+0

謝謝傑米,現在工作!我只跟2集測試,我會去,現在更多的測試! – user1004299 2012-02-17 03:31:51