特定列的行数和最后一行的显示

时间:2016-07-27 15:03:45

标签: sql-server sql-server-2008

我必须计算列中相同值的行数,并显示最后一列的计数值。以下是我的方案

表1

Col_A  Col_B   Col_C
a      1       a1
a      2       a2
a      3       a3
a      4       a4
a      5       a5
a      6       a6
b      7       a7
b      8       a8
b      9       a9
b      10      a10
e      7       a11
e      1       a12
e      4       a13

在显示数据时,我应该在COL_A中计算相同的值并显示如下所示

Col_A  Col_B   Col_C   Col_D
a      1       a1   
a      2       a2   
a      3       a3   
a      4       a4   
a      5       a5   
a      6       a6      6
b      7       a7   
b      8       a8   
b      9       a9   
b      10      a10     4
e      7       a11  
e      1       a12  
e      4       a13     3

谢谢,

3 个答案:

答案 0 :(得分:0)

这是一种方法。 Lead()用于检查这是否是集合的最后一行,row_number用于计算行数:

select Col_A, Col_B, Col_C, case when isnull(NextA,'') != Col_A then RN end
from (
  select 
    *, 
    row_number() over (partition by Col_A order by Col_C) as RN,
    lead(Col_A) over (order by Col_A, Col_C) as NextA
  from Table1
) X

2008年使用反向行号也应该有效:

select Col_A, Col_B, Col_C, case when RN2 = 1 then RN end
from (
  select 
    *, 
    row_number() over (partition by Col_A order by Col_C asc) as RN,
    row_number() over (partition by Col_A order by Col_C desc) as RN2
  from Table1
) X

答案 1 :(得分:0)

你可以查看row_number是否等于count()over(),如果是,则显示count

SELECT  [Col_A], 
        [Col_B], 
        [Col_C],
        (CASE WHEN ROW_NUMBER() OVER (PARTITION BY [Col_A] ORDER BY [Col_B]) = COUNT(*) OVER (PARTITION BY COL_A) 
            THEN COUNT(*) OVER (PARTITION BY COL_A) END) AS Col_D
FROM    Table1

答案 2 :(得分:0)

SQL 2008有ROW_NUMBER()

<强> DEMO

SELECT X.*,  (CASE WHEN rn=1 THEN total END) as count_A
FROM ( SELECT Col_A, 
              Col_B, 
              Col_C, 
              row_number() over 
                (partition by Col_A order by Col_C DESC) as rn
       from test
     ) X
join (
       SELECT [Col_A] , 
              count([Col_A]) as total
       FROM test GROUP BY [Col_A]
    ) Y
   ON X.[Col_A] = Y.[Col_A]
ORDER BY X.Col_A,          
         X.Col_C 

输出

enter image description here

编辑v2.0:这可能也应该有用,不需要JOIN

SELECT X.*, 
       (CASE WHEN rn=1 
             THEN MAX(rn) OVER (partition BY X.col_a) 
        END) as count_A 
FROM ( SELECT Col_A, 
              Col_B, 
              Col_C, 
              row_number() over (partition by Col_A order by Col_C DESC) as rn
       from test
     ) X
ORDER BY X.Col_A,          
         X.Col_C