在单个查询中获取行数和不同行数的最佳方法
best way to get count and distinct count of rows in single query
在单个查询中获取行数和不同行数的最佳方法是什么?
要获得不同的计数,我们可以像这样使用子查询:
select count(*) from
(
select distinct * from table
)
我有超过 15 列,也有很多重复的行,我想计算一个查询中的行数以及不同的行数。
如果我用这个会更多
select count(*) as Rowcount , count(distinct *) as DistinctCount from table
这不会给出准确的结果,因为 count(distinct *)
不起作用。
我想我已经明白你在找什么了。您需要使用一些 window 函数。
因此,您的查询应该类似于 =>
Select COUNT(*) OVER() YourRowcount ,
COUNT(*) OVER(Partition BY YourColumnofGroup) YourDistinctCount --Basic of the distinct count
FROM Yourtable
新更新
select top 1
COUNT(*) OVER() YourRowcount,
DENSE_RANK() OVER(ORDER BY YourColumn) YourDistinctCount
FROM Yourtable ORDER BY TT DESC
注意:这段代码写在sql服务器端。请检查代码并告诉我。
create table tbl
(
col int
);
insert into tbl values(1),(2),(1),(3);
select count(*) as distinct_count, sum(sum) as all_count
from (
select count(col) sum from tbl group by col
)A
为什么不直接将子查询放在另一个查询中?
select count(*),
(select count(*) from (select distinct * from table))
from table;
在单个查询中获取行数和不同行数的最佳方法是什么?
要获得不同的计数,我们可以像这样使用子查询:
select count(*) from
(
select distinct * from table
)
我有超过 15 列,也有很多重复的行,我想计算一个查询中的行数以及不同的行数。
如果我用这个会更多
select count(*) as Rowcount , count(distinct *) as DistinctCount from table
这不会给出准确的结果,因为 count(distinct *)
不起作用。
我想我已经明白你在找什么了。您需要使用一些 window 函数。
因此,您的查询应该类似于 =>
Select COUNT(*) OVER() YourRowcount ,
COUNT(*) OVER(Partition BY YourColumnofGroup) YourDistinctCount --Basic of the distinct count
FROM Yourtable
新更新
select top 1
COUNT(*) OVER() YourRowcount,
DENSE_RANK() OVER(ORDER BY YourColumn) YourDistinctCount
FROM Yourtable ORDER BY TT DESC
注意:这段代码写在sql服务器端。请检查代码并告诉我。
create table tbl
(
col int
);
insert into tbl values(1),(2),(1),(3);
select count(*) as distinct_count, sum(sum) as all_count
from (
select count(col) sum from tbl group by col
)A
为什么不直接将子查询放在另一个查询中?
select count(*),
(select count(*) from (select distinct * from table))
from table;