2011-10-21 47 views
1

我怎樣才能同時使用select語句和select語句?用一個sql查詢選擇行數和列數?

+0

您必須對您的問題展開。你的數字是什麼意思?在一個正常的'SELECT'語句中,你會明確地提供列... –

+0

@ElRonnoco我編輯了這個問題..好好看看它.. – Satya

+0

你需要顯示你的查詢語句。至少對我來說,這仍然不清楚。 – Yuck

回答

1

如果你只是想看看你的表格有什麼「形狀」,這樣的事情會起作用。但是,如果你想知道列/行數爲給定的查詢,也可能是可能的,但我不知道該怎麼辦呢

; WITH ROW_COUNTS AS 
(
SELECT 
    s.[Name] as [SchemaName] 
, t.[name] as [TableName] 
, SUM(p.rows) as [RowCounts] 
FROM 
    sys.schemas s 
    LEFT JOIN 
     sys.tables t 
     ON s.schema_id = t.schema_id 
    LEFT JOIN 
     sys.partitions p 
     ON t.object_id = p.object_id 
    LEFT JOIN 
     sys.allocation_units a 
     ON p.partition_id = a.container_id 
WHERE 
    p.index_id in(0,1) -- 0 heap table , 1 table with clustered index 
    AND p.rows is not null 
    AND a.type = 1 -- row-data only , not LOB 
GROUP BY 
    s.[Name] 
, t.[name] 
) 
, COLUMN_COUNTS AS 
(
SELECT 
    s.[Name] as [SchemaName] 
, t.[name] as [TableName] 
, COUNT(c.column_id) as [ColumnCounts] 
FROM 
    sys.schemas s 
    INNER JOIN 
     sys.tables t 
     ON s.schema_id = t.schema_id 
    INNER JOIN 
     sys.columns c 
     ON C.object_id = T.object_id 
GROUP BY 
    s.[Name] 
, t.[name] 
) 
SELECT 
    CC.SchemaName 
, CC.TableName 
, RC.RowCounts 
, CC.ColumnCounts 
FROM 
    COLUMN_COUNTS CC 
    INNER JOIN 
     ROW_COUNTS RC 
     ON RC.SchemaName = CC.SchemaName 
     AND RC.TableName = CC.TableName 
ORDER BY 
    1,2 

結果對主

SchemaName TableName    RowCounts ColumnCounts 
dbo   Hold_Cluster_Status  0   10 
dbo   MSreplication_options 3   6 
dbo   spt_fallback_db   0   8 
dbo   spt_fallback_dev  0   10 
dbo   spt_fallback_usg  0   9 
dbo   spt_monitor    1   11 
dbo   spt_values    2506  6 
0

我跑又不是100%URE你想要什麼,但這裏是一個可能的例子...

SELECT 
    a, 
    b, 
    c, 
    (SELECT COUNT(*) FROM yourTable) as table_count 
FROM 
    yourTable 
2

使用,你應該能夠完成你在找什麼做一個COUNT()窗口集合。然而,對一個非常大的表,DISTINCT是不太可能是非常高性能:

SELECT DISTINCT a, b, c, COUNT(*) OVER (PARTITION BY 1) FROM <tablename>; 

另一種選擇是,但你兩次觸摸表:

SELECT a,b,c, MyCount 
FROM <tablename> 
CROSS JOIN 
    (SELECT COUNT(*) AS MyCount 
    FROM <tablename> 
    ) 
+1

順便說一句:'COUNT(*)OVER()'具有相同的效果。 –