[英]How to get count of CTE result?
I am new to sql, I have created a CTE now I want to get the count of rows from CTE result set 我是sql的新手,我现在创建了一个CTE,我想从CTE结果集中获取行数
DECLARE @start_date date,@end_date DATE ;
select @start_date= min(ETA) from [dbo].[testTable]
select @end_date=max(ETA) from [dbo].[testTable];
;WITH AllDays
AS (
SELECT @start_date AS [Date]
--, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
--, [level] + 1
FROM AllDays
WHERE [Date] < @end_date )
--Insert into #tempETA (CallETA)
SELECT [Date]--, [level]
FROM AllDays OPTION (MAXRECURSION 0)
select count(a.Date),a.Date from AllDays a
I am getting error here: 我在这里遇到错误:
(1048 row(s) affected)
Msg 208, Level 16, State 1, Line 20
Invalid object name 'AllDays'.
A CTE
can hold temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE
. CTE
可以保存在单个SELECT, INSERT, UPDATE, DELETE
的执行范围内定义的临时结果集。 You cannot have another SELECT
outside the scope of CTE
您不能在
CTE
范围之外拥有另一个SELECT
Use @@ROWCOUNT
to get the count of CTE
. 使用
@@ROWCOUNT
获取CTE
计数。 Considering you want the CTE
result and its count. 考虑到您需要
CTE
结果及其数量。
SELECT [Date]--, [level]
FROM AllDays OPTION (MAXRECURSION 0)
select @@ROWCOUNT
If you want to count to be part of your result then use COUNT() OVER()
如果您想算作结果的一部分,请使用
COUNT() OVER()
SELECT [Date],count(1)over() as Total_count
FROM AllDays OPTION (MAXRECURSION 0)
Check out this below code and tell.is this what you want to get.? 看看下面的代码,然后告诉。这是您想要得到的吗?
DECLARE @start_date date,@end_date DATE ;
select @start_date= min(ETA) from [dbo].[testTable]
select @end_date=max(ETA) from [dbo].[testTable];
;WITH AllDays
AS (
SELECT @start_date AS [Date]
--, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, @start_date)
--, [level] + 1
FROM [testTable]
WHERE @start_date < @end_date )
--Insert into #tempETA (CallETA)
--SELECT [Date]--, [level]
--FROM AllDays OPTION (MAXRECURSION 0)
select count(a.Date) from AllDays a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.