我怎样才能多次使用CTE表

时间:2014-02-09 18:29:25

标签: sql sql-server

With CTETable as
(
   select * from table
)

Select * from CTETable --one time

Select sum(column) from CTETable -- 2nd time

Select count(column) from CTETable -- 3rd time

请帮忙。

2 个答案:

答案 0 :(得分:1)

您不能在多个查询中使用CTE。但另外,您可以通过从现有CTE为Sum或Count目的制作另一个CTE并将它们交叉连接来使用它。

见下面的查询。

With CTETable as
(
   select * from Table
), CTETotal As 
(
   SELECT COUNT(count) 'count' 
   from CTETable
) 
Select * from CTETable 
CROSS JOIN CTETotal

答案 1 :(得分:0)

CTE只能在一个查询中使用。因此,只需将UNION ALL的各个查询加入到一个查询中即可。您可以使用额外的人工行来区分不同的结果集。

请参阅here for a fiddle

With CTETable as
(
   select * from TestTable
)
Select '*',* from CTETable --one time
UNION ALL
Select 'sum', sum(col) from CTETable -- 2nd time
UNION ALL
Select 'count', count(col) from CTETable -- 3rd time
相关问题