从查询

时间:2018-05-18 04:33:09

标签: sql sql-server sql-server-2005

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

TableName | ColumnName | SomeColumn

我可以以某种方式增强此查询,以便对于来自该结果集的每条记录,我会得到count of elements from that 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

以上查询无效。发生错误:"无效的对象名称&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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

如果要查询返回的行数,请在每行的单独列中使用窗口函数:

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