Select 来自查询的表

Select on tables from query

在 SQL Server 2005 中,我进行了一个生成具有以下属性的结果集的查询:

TableName | ColumnName | SomeColumn

我能否以某种方式增强此查询,以便对于该结果集中的每条记录,我将获得 count of elements from that table(或者通常对 table 和 TableName、ColumnName 上指定的列执行任何查询?能不能实现这样的:

SELECT *, (SELECT COUNT(*) FROM Q.TableName) AS Cnt, (SELECT AVG(SomeColumn) FROM Q.TableName) AS AvgValue

FROM 
(`...OMITTED ORIGINAL QUERY...`) AS Q

?

以上查询无效。出现错误:"Invalid object name 'Q.TableName'"。

这在 SQL Server 2005 中仅使用简单查询(没有存储过程)是否可行?

示例数据:

TableName | ColumName 

SomeTable1 | Column11
SomeTable1 | Column12
SomeTable2 | Column21
SomeTable2 | Column22
SomeTable3 | Column31

我希望 sample data 中的每一行都有更多属性:

TableName | ColumName | CountInThatTable | AvgValueInThatColumnFromThatTable

SomeTable1 | Column11 | N1               | N11
SomeTable1 | Column12 | N1               | N12
SomeTable2 | Column21 | N2               | N21
SomeTable2 | Column22 | N2               | N22
SomeTable3 | Column31 | N3               | N31

如果您想通过查询计算行数 returns,在每行的单独列中,然后使用 window 函数:

select . . .,
       count(*) over () as overall_cnt
from . . .;

如果我正确理解了您的问题,那么要获得您的结果,您需要一个动态查询。 下面是一个示例,您可以利用它来实现您的结果。

DECLARE @TableName VARCHAR(100)
CREATE TABLE #tblRowCount (Id INT IDENTITY(1,1),
                           TableName VARCHAR(100), 
                           NoOfRows int)
DECLARE cur_trav  CURSOR FOR SELECT Name FROM sys.tables
OPEN cur_trav
FETCH NEXT FROM cur_Trav INTO @tableName
DECLARE @SQL VARCHAR(5000)

WHILE @@FETCH_STATUS =0
BEGIN
SET @SQL =''
SET @SQL = ' INSERT INTO #tblRowCount (tableName, NoOfRows)  SELECT ''' + @TableName +''' as tableName , COUNT(1) as counter FROM ' + @TableName 
EXECUTE(@SQL)
--  --PRINT @sql
  FETCH NEXT FROM cur_Trav  
END 
CLOSE cur_Trav
DEALLOCATE cur_trav

SELECT Id,tableName, NoOfRows FROM #tblRowCount
DROP TABLE #tblRowCount