所以我试图解决的问题是我有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,但我不确定那会是什么......谢谢!
答案 0 :(得分: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;
答案 1 :(得分: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