簡體   English   中英

數據集SQL Server中的不同ID計數

[英]Count of distinct ID in dataset SQL Server

以下是示例查詢:

我想要的是為每個記錄填充每個RWL的不同id的計數。

我想在一個查詢中執行它,因為我的實際數據集非常大。

create table temp_ayush
(id int,
RWL varchar(10),
cost int)

insert into temp_ayush
values
(1,'ABC',100),
(1,'ABC',200),
(2,'XYZ',300),
(2,'ABC',100)

select * 
,count(id) over (partition by RWL)
from temp_ayush

而不是使用RWL分區,而是使用GROUP BYCOUNT DISTINCT ,如下所示:

select RWL
,count(distinct id) 
from temp_ayush
group by RWL

請注意,因為它使用GROUP BY ,所以您只能選擇group by子句中包含的列。

如果您需要其他列,我建議在連接中使用上述內容,如下所示:

SELECT  RWL,
        IdCount,
        Cost
FROM    temp_ayush
JOIN    (    select RWL
            ,count(distinct id) 
            from temp_ayush
            group by RWL
        )   T
ON      T.RWL = RWL
create table #temp_ayush
(id int,
RWL varchar(10),
cost int)

insert into #temp_ayush
values
(1,'ABC',100),
(1,'ABC',200),
(2,'XYZ',300),
(2,'ABC',100)

select t.* 
,c.Cnt
from #temp_ayush t
    JOIN (
        SELECT RWL, COUNT (DISTINCT ID) AS Cnt
        FROM #temp_ayush
        GROUP BY RWL
    ) c ON c.RWL = t.RWL

drop table #temp_ayush

嘗試以下查詢之一:

1)如果要模仿窗口函數( count(distinct ..)不能用作窗口函數),請使用:

select id,
       RWL,
       (select count(distinct ID) from temp_ayush where RWL = ta.RWL) countDistinct,
       cost
from temp_ayush ta

2)如果你想分組,使用:

select RWL, count(distinct ID) from temp_ayush
group by RWL

我想你想要一個相關的子查詢:

select  *, (select count(distinct id) from #temp_ayush b where a.rwl = b.rwl)
from    #temp_ayush a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM