admin

为每个用户获取行,其中列中的值计数最大

sql

我的专栏结构:

Column0   Column1
aaa        abc
aaa        abc
aaa        xyx
aaa        NA
bbb        fgh
bbb        NA
bbb        NA
bbb        NA
ccc        NA
ccc        NA
ccc        NA
ccc        NA

我希望得到的是每个计数最大的不同“ Column0”数据“ Column1”数据,除非该数据为NA,在这种情况下获得第二高的数据。如果对于“
Column0”数据,“ Column1”的所有值均为NA,则该值可以为NA

因此,期望值:

Column0   Column1
aaa       abc
bbb       fgh
ccc       NA

阅读 185

收藏
2021-06-07

共1个答案

admin

这将给出正确的结果:

DECLARE @t table(Column0  char(3), Column1 varchar(3))
INSERT @t values
('aaa','abc'),('aaa','abc'),('aaa','xyx'),('aaa','NA')
,('bbb','fgh'),('bbb','NA'),('bbb','NA'),('bbb','NA')
,('ccc','NA'),('ccc','NA'),('ccc','NA'),('ccc','NA')

;WITH CTE as
(
  SELECT
    column0, 
    column1, 
    count(case when column1 <> 'NA' THEN 1 end) over (partition by column0, column1) cnt
  FROM @t
), CTE2 as
(
  SELECT 
    column0, 
    column1, 
    row_number() over (partition by column0 order by cnt desc) rn
  FROM CTE
)
SELECT column0, column1
FROM CTE2
WHERE rn = 1

结果:

column0  column1
aaa      abc
bbb      fgh
ccc      NA
2021-06-07