[英]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 *)
不起作用。
你為什么不把子查詢放在另一個查詢中呢?
select count(*),
(select count(*) from (select distinct * from table))
from table;
我想我已經明白你在找什么了。 您需要使用一些 window function。
所以,你的查詢應該看起來像 =>
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.