0

我有多个数据库,它们都包含相同的结构但不同的内容,A001、A002、A003、A004 ......如下:

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

关于如何进行分组有点令人困惑,如果有一种方便的循环方式或其他东西,我不必为每个 A001 到 A020 重复。这在 SQL 中可能吗?特别是使用多个数据库(A001和A002....都是同一台服务器上的不同数据库)

4

2 回答 2

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
于 2012-12-06T00:10:59.643 回答
0

您必须静态指定所有数据库名称、表名称和列(它们必须是常量)。这意味着您可以手动编写此查询或构建 SQL 字符串(在 T-SQL 中或在客户端上)并动态执行它。

于 2012-12-05T23:26:02.947 回答