下面是示例查询:
我想要的是针对每条记录填充每个 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 BY
和COUNT DISTINCT
,如下所示:
select RWL
,count(distinct id)
from temp_ayush
group by RWL
请注意,由于这使用了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