在SQL Server中查找派生表的记录计数

时间:2019-06-18 09:19:52

标签: sql sql-server

CREATE  TABLE   Temp
(
   ID   Int IDENTITY,
   Name Varchar(100)
)

INSERT  INTO    Temp
SELECT  'Elby'
UNION ALL
SELECT  'Eljo'
UNION ALL
SELECT  'Elsy'
UNION ALL
SELECT  'Elsy'
UNION ALL
SELECT  'Eljo'
UNION ALL
SELECT  'Elsy'
UNION ALL
SELECT  'Elsy'

我要求的输出是..

    ----------------------------------------
    TotalRecordCount        ID      Name
    ----------------------------------------
    7                       5       Elby
    7                       6       Eljo
    7                       7       Elsy
    7                       8       Elsy
    ----------------------------------------    

我的查询是...

SELECT  TotalRecordCount,
        ID,
        Name        
FROM    (
        SELECT  *
        FROM    Temp
      ) Tab1
WHERE   ID > 4

我的问题是,如何找到“ TotalRecordCount”字段的值。这是表“ Temp”的总数。

我不能使用像'SELECT COUNT(*) FROM Temp AS TotalRecordCount'这样的查询,因为它不是单个表。

就像(SELECT * FROM Table1 JOIN TABLE2 ON (Table1.ID = Table2.ID) JOIN TABLE3 ON (TABLE2.ID = TABLE3.ID) JOIN TABLE4 ON (TABLE3.ID = TABLE4.ID).....

为您的理解,我使用了'temp'而不是整个查询。

3 个答案:

答案 0 :(得分:5)

您可以使用CTE和窗口函数来执行此操作,以避免对表进行第二次扫描:

WITH Counts AS(
    SELECT ID,
           [Name],
           COUNT(*) OVER () AS TotalRows
    FROM dbo.Temp)
SELECT TotalRows,
       ID,
       [Name]
FROM Counts
WHERE ID > 4;

答案 1 :(得分:2)

为了娱乐,您可以执行此操作而无需子查询或CTE:

select top (1) with ties t.*, count(*) over () as cnt
from temp t
order by (case when id > 4 then 1 else 2 end)

答案 2 :(得分:1)

因此,示例中的“温度”是一些您不想重复的大型复杂查询的占位符。通用表表达式可用于此类事情:

WITH cteTemp AS (
    SELECT *
    FROM Temp
)
SELECT (SELECT COUNT(*) FROM cteTemp) AS TotalRecordCount,
      ID,
      Name
FROM cteTemp
WHERE ID > 4