我有这样的查询:
USE [MyDataBase]
GO
DECLARE @day DATE = '2017-05-18'
DECLARE @camp VARCHAR(500) = '9015';
WITH ODCALLS AS (SELECT * FROM [dbo].[ODCalls_2017_05]
WHERE CONVERT(DATE, CallLocalTime) = @day AND LastCampaign = @camp AND CallType = 1
)
SELECT COUNT(*) FROM ODCALLS -- this returns 2998
SELECT DATEPART(HOUR, CallLocalTime) AS dHOUR, COUNT(*) AS [Calls Received]
FROM ODCALLS
GROUP BY DATEPART(HOUR, CallLocalTime)
ORDER BY dHOUR -- this returns 24 rows as there are 24 hours in a day
SELECT COUNT(*) FROM ODCALLS -- this returns 2907
实例是SQL SERVER EXPRESS 2014,OdCalls_2017_05
表中的数据不会改变,这里是结果的预览:
我不知道为什么会这样,有人有任何解释吗?
由于
答案 0 :(得分:2)
我很惊讶这完全奏效。公用表表达式不就像临时表一样。该查询用作下一个查询的输入(如View可以),并且可以跨后续查询和CTE执行优化,因此CTE的结果集可能永远不会存在。
随后对CTE的调用不起作用,因为这违反了CTE的定义。有关详情,请参阅https://blogs.sentryone.com/aaronbertrand/backtobasics-ctes/。