如何通过一个陈述来选择计数和选择列?
答案 0 :(得分:2)
使用COUNT()窗口聚合,您应该能够完成您想要做的事情。但是,针对非常大的表的DISTINCT不太可能具有高性能:
SELECT DISTINCT a, b, c, COUNT(*) OVER (PARTITION BY 1) FROM <tablename>;
另一种选择是,但你要触摸桌子两次:</ p>
SELECT a,b,c, MyCount
FROM <tablename>
CROSS JOIN
(SELECT COUNT(*) AS MyCount
FROM <tablename>
)
答案 1 :(得分: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
答案 2 :(得分:0)
我不是100%你想要的,但这是一个可能的例子......
SELECT
a,
b,
c,
(SELECT COUNT(*) FROM yourTable) as table_count
FROM
yourTable