0

所以我要解决的问题是我有 8 个表,其中包含数据。第 9 个表,每个表都有一个字段,我想存储前 8 个表中的每一个的计数。我能够返回计数,但是不是每个字段一个计数,我有 8 行只是填充第一个字段。8 个表名中的每一个都是第 9 个表中的一个字段名。这是我的代码:

SELECT COUNT(SubID) as Sent_Members FROM Sent_Members
UNION ALL
SELECT COUNT(SubID) as Sent_Shoppers FROM Sent_Shoppers
UNION ALL
SELECT COUNT(SubID) as Open_Members FROM Open_Members
UNION ALL
SELECT COUNT(SubID) as Open_Shoppers FROM Open_Shoppers
UNION ALL
SELECT COUNT(SubID) as Click_Members FROM Click_Members
UNION ALL
SELECT COUNT(SubID) as Click_Shoppers FROM Click_Shoppers
UNION ALL
SELECT COUNT(SubID) as Unique_Click_Members FROM Unique_Click_Members
UNION ALL
SELECT COUNT(SubID) as Unique_Click_Shoppers FROM Unique_Click_Shoppers

我猜我应该使用一些东西而不是 Union,但我不确定那会是什么.. 谢谢!

4

2 回答 2

4

这看起来更丑陋,但它比执行 8 个子查询并在每个子查询中进行完整的表扫描效率高数百倍。

;WITH r AS
(
  SELECT t.name, rc = SUM(p.rows)
   FROM sys.tables AS t
   INNER JOIN sys.partitions AS p
   ON t.[object_id] = p.[object_id]
   WHERE p.index_id IN (0,1)
   AND t.name IN 
   (
    N'Sent_Members',
    N'Sent_Shoppers',
    N'Open_Members',
    N'Open_Shoppers',
    N'Click_Members',
    N'Click_Shoppers',
    N'Unique_Click_Members',
    N'Unique_Click_Shoppers'
   )
   GROUP BY t.name
)
SELECT * FROM r 
PIVOT (MAX(rc) FOR name IN 
(
 [Sent_Members],
 [Sent_Shoppers],
 [Open_Members],
 [Open_Shoppers],
 [Click_Members],
 [Click_Shoppers],
 [Unique_Click_Members],
 [Unique_Click_Shoppers]
) AS p;
于 2013-04-16T20:21:47.337 回答
3

干得好:

INSERT INTO [Table9]
SELECT 
    (SELECT COUNT(*) FROM Sent_Members) AS Sent_Members,
    (SELECT COUNT(*) FROM Sent_Shoppers) AS Sent_Shoppers,
    (SELECT COUNT(*) FROM Open_Members) AS Open_Members,
    (SELECT COUNT(*) FROM Open_Shoppers) AS Open_Shoppers,
    (SELECT COUNT(*) FROM Click_Members) AS Click_Members,
    (SELECT COUNT(*) FROM Click_Shoppers) AS Click_Shoppers,
    (SELECT COUNT(*) FROM Unique_Click_Members) AS Unique_Click_Members,
    (SELECT COUNT(*) FROM Unique_Click_Shoppers) AS Unique_Click_Shoppers
于 2013-04-16T20:10:52.810 回答