2012-12-05 43 views
0

我有多個數據庫均含有相同的結構,但不一樣的內容,A001,A002,A003,A004 A020 ....什麼是重新制定查詢在很短的&的最快方法便捷的方式讓我可以得到表輸出如下:SQL Server的多個數據庫連接和總結

Code | Desc | A001 | A002 | A003 | A004 
=====+======+======+======+======+======= 
ABCD | ABCD | 0 | 1 | 3 | 4 

的查詢是A001如下如何做分組

SELECT AC1.cCode, SUM(AC1.cQtyin) - SUM(AC1.cQtyout) AS A001, AB1.cDes 
FROM 
A001.dbo.pmStock AC1 
INNER JOIN 
A001.dbo.pmProduct AB1 ON AC1.Id = AB1.Prid 
GROUP BY AC1.cCode, AB1.cDes 

它有點混亂,如果那裏有一個方便的方式循環或什麼,我不必重申每個A00 1至A020。這在SQL中可能嗎?尤其是在使用多個數據庫(A001和A002 ....都在同一臺服務器上的所有不同的數據庫)

+0

如果ABCD存在於A001中,它是否也存在於所有其他數據庫表中? – MatBailie

+0

那是正確的,只是量的值是不同的,從不同的代碼僅用於識別產品,但其複製很多很多次 – Akshat

回答

1

我在我的iPhone,所以這是一個有點頭疼的輸入。但是,以下可能至少可以維持一點。將子查詢放入視圖可能是值得的。

SELECT 
    Product.cDes, 
    Stock.cCode, 
    SUM(CASE WHEN Stock.source = 'A001' THEN Stock.amount ELSE 0 END) AS A001, 
    SUM(CASE WHEN Stock.source = 'A002' THEN Stock.amount ELSE 0 END) AS A002, 
    SUM(CASE WHEN Stock.source = 'A003' THEN Stock.amount ELSE 0 END) AS A003, 
    Etc, Etc 
FROM 
    A001.dbo.Product 
INNER JOIN 
(
    SELECT 'A001' AS source, id, cCode, cQtyIn - cQtyOut AS amount FROM A001.dbo.pmStock 
    UNION ALL 
    SELECT 'A002' AS source, id, cCode, cQtyIn - cQtyOut AS amount FROM A002.dbo.pmStock 
    UNION ALL 
    SELECT 'A003' AS source, id, cCode, cQtyIn - cQtyOut AS amount FROM A003.dbo.pmStock 
    UNION ALL 
    Etc, etc 
) 
    AS Stock 
    ON Stock.Id = Product.Prid 
GROUP BY 
    Stock.cCode, 
    Product.cDes 
0

你要靜態指定所有的數據庫名,表名和列(它們必須是常量)。這意味着,你可以手工編寫這個查詢或建立一個SQL字符串(無論是在T-SQL或客戶端)和動態執行。